如何使用Jest模拟JavaScript窗口对象? [英] How to mock the JavaScript window object using Jest?
本文介绍了如何使用Jest模拟JavaScript窗口对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要测试一个在浏览器中打开新标签的功能
I need to test a function which opens a new tab in the browser
openStatementsReport(contactIds) {
window.open(`a_url_${contactIds}`);
}
我想模拟窗口的打开功能,这样我就可以验证正确的URL传入open函数。
I would like to mock the window's open function so I can verify the correct URL is passed in to the open function.
使用Jest,我不知道如何模拟窗口。我尝试使用模拟函数设置window.open但这种方式不起作用。以下是测试用例
Using Jest, I don't know how to mock the window. I tried to set window.open with a mock function but this way doesn't work. Below is the test case
it('correct url is called', () => {
window.open = jest.fn();
statementService.openStatementsReport(111);
expect(window.open).toBeCalled();
});
但是它给了我错误
expect(jest.fn())[.not].toBeCalled()
jest.fn() value must be a mock function or spy.
Received:
function: [Function anonymous]
我该怎么做测试用例?任何建议或提示表示赞赏
what should I do to the test case? any suggestions or hints are appreciated
推荐答案
而不是窗口
使用全球
it('correct url is called', () => {
global.open = jest.fn();
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
你也可以尝试
const open = jest.fn()
Object.defineProperty(window, 'open', open);
这篇关于如何使用Jest模拟JavaScript窗口对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文