</p>

function timerGame(callback) {
console.log('Ready....go!');
setTimeout(() => {
console.log('Times up -- stop!');
callback && callback();
}, 1000);

setTimeout(() => {
console.log('Times up -- stop!');
}, 2000);
}

test('waits 1 second before ending the game', () => {
jest.useFakeTimers();
const callback = jest.fn();

timerGame(callback);

expect(setTimeout.mock.calls.length).toBe(2);
console.log(setTimeout.mock);
expect(setTimeout.mock.calls[1][1]).toBe(2000);
jest.runAllTimers();
// Now our callback should have been called!
expect(callback).toBeCalled();
expect(callback.mock.calls.length).toBe(1);
});
参考: http://facebook.github.io/jest/docs/zh-Hans/timer-mocks.html#content

</body></html>

转载请注明:WebLogic Android 博客 » Jest单元测试之模拟时间