【发布时间】:2019-04-10 19:18:21
【问题描述】:
我有一个简单的函数,它在 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 的模拟看起来工作正常,因为测试通过了。
只是想知道是否有人可以引导我朝着正确的方向前进。提前致谢。
【问题讨论】:
-
尝试使测试用例异步。
-
我试过了,但仍然是同样的失败测试。也许我的语法错误? it('调用 open', async () => { foo(); await setTimeout(); expect(global.open).toBeCalled(); });
-
试试这个。
it('calls open', async() => { foo(); await expect(global.open).toBeCalled(); }); -
谢谢 - 但这没有用
-
在运行检查之前您是否尝试过
jest.runAllTimers()?
标签: javascript unit-testing jestjs