假设我有一个组件,它呈现一个简单的 div,其中包含一个从 0 开始并每秒递增 1 的整数。因此,5 秒后,组件应呈现“5”,30 秒后,应呈现“30”,依此类推。如果我想测试这个组件并确保它在 5 秒后呈现出应有的效果,我可能会写这样的内容。
it('should render <5> after 5 seconds', () => {
const time = mount(<Timer/>)
setTimeout(() => {
expect(time.text()).toEqual('5')
}, 5000)
})
但是,这不起作用,因为测试从未真正运行预期并无论如何都返回通过。即使它确实有效,使用这样的超时也会非常低效,因为测试必须等待 5 秒钟。如果我想模拟更长的时间怎么办?经过一番搜索,我发现 jest 实际上有一个 timer mock但我似乎不知道如何在这种情况下实现它。任何帮助将不胜感激。谢谢!
最佳答案
为了让 Jest 知道您的测试是异步的,您需要:1) 返回 Promise,或 2) 在测试回调中声明一个参数,如下所示:
it('should render <5> after 5 seconds', done => {
// test stuff
});
来源:https://facebook.github.io/jest/docs/en/asynchronous.html
为了让你的测试工作:
it('should render <5> after 5 seconds', done => {
jest.useFakeTimers(); // this must be called before any async things happen
const time = mount(<Timer/>);
setTimeout(() => {
// Note the placement of this try/catch is important.
// You'd think it could be placed most anywhere, but nope...
try {
// If this assertion fails, an err is thrown.
// If we do not catch()...done.fail(e) it,
// then this test will take jasmine.DEFAULT_TIMEOUT_INTERVAL (5s unless you override)
// and then fail with an unhelpful message.
expect(time.text()).toEqual('5');
done();
} catch(e) {
done.fail(e);
}
}, 5000);
jest.runTimersToTime(5000); // This basically fast forwards 5s.
});
关于javascript - 如何使用 jest 在一定时间的模拟时间后运行断言测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40751534/