gpt4 book ai didi

javascript - Jest – 模拟窗口或文档对象

转载 作者:行者123 更新时间:2023-11-29 17:49:38 26 4
gpt4 key购买 nike

如何使用 Jest 模拟(然后测试)Window 或 Document 对象?特别是当它具有可能尚未在您正在测试的文件中定义的嵌套函数时,例如

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 = 做类似的事情。但这当然太容易了,而且行不通。

最佳答案

如果您还没有找到答案,您应该能够像这样模拟它:

  postMessageMock = jest.fn();
Object.defineProperty(window, 'webkit', {
value: { messageHandlers: { execute: { postMessage: postMessageMock } } },
});

关于javascript - Jest – 模拟窗口或文档对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45200395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com