Jest Mock 计时器
测试超时的最大障碍之一是等待超时。Jest提供了一种解决方法。
运行所有定时器
假设您正在测试一个程序,该程序会在一段时间后发出一个事件,但您不想等待该事件实际发出的时间太长。Jest 为您提供了通过setTimeout
函数立即运行设置的回调的选项jest.runAllTimers
。
// This has to be called before using fake timers.
jest.useFakeTimers();
it('closes some time after being opened.', (done) => {
// An automatic door that fires a `closed` event.
const autoDoor = new AutoDoor();
autoDoor.on('closed', done);
autoDoor.open();
// Runs all pending timers. whether it's a second from now or a year.
jest.runAllTimers();
});
运行定时器到时间
但如果你不想运行所有计时器怎么办?如果你只想模拟一些时间流逝?runTimersToTime
就在这里等着你。
jest.useFakeTimers();
it('announces it will close before closing.', (done) => {
const autoDoor = new AutoDoor();
// The test passes if there's a `closing` event.
autoDoor.on('closing', done);
// The test fails if there's a `closed` event.
autoDoor.on('closed', done.fail);
autoDoor.open();
// Only move ahead enough time so that it starts closing, but not enough that it is closed.
jest.runTimersToTime(autoDoor.TIME_BEFORE_CLOSING);
});