我有一个简单的函数,它在setTimeout中打开一个新窗口,并想测试打开的窗口是否被调用。
export function foo() {
setTimeout(() => {
window.open('http://google.com');
}, 0);
}
describe('foo', () => {
beforeEach(() => {
jest.useFakeTimers();
global.open = jest.fn();
});
it('calls open', () => {
foo();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(global.open).toBeCalled(); //FAILING
});
});
目前我的期望是失败了“预期模拟功能被调用”。当我从我的函数中删除setTimeout时,window.open的模拟看起来工作正常,因为测试通过了。
只是想知道是否有人可以引导我朝着正确的方向前进。提前致谢。
你可以嘲笑你的global.open
并检查它是否在执行foo()
时被调用:
it('calls open', (done) => {
global.open = jest.fn(); // mocking global.open
foo(); // calling foo()
setTimeout(()=> {
expect(global.open).toBeCalled()
done()
})
})