0
如何用Jest模擬(然後測試)窗口或文檔對象?特別是當它嵌套函數可能還沒有定義在你正在測試的文件中時Jest - 模擬窗口或文檔對象
const foo = (payload) => {
window.webkit.messageHandlers.execute.postMessage(payload)
return true
}
// Jest: TypeError: Cannot read property 'messageHandlers' of undefined'
同樣,你會如何模擬document.location
?例如。
const bar = (nonce, payload) => {
document.location = 'native://somefeature/send?nonce=' + nonce + '&payload=' + payload
return true
}
我要去的方向:
describe('foo',() => {
it('posts a message',() => {
const payload = 'payload'
window.webkit.messageHandlers.execute.postMessage = jest.fn()
let result = foo(payload)
expect(window.webkit.messageHandlers.execute.postMessage).toHaveBeenCalledWith(payload)
})
})
我猜你會做document.location =
類似的東西。但是,當然這太容易了,而且不起作用。