一、mock timers的使用
// timer.js
export const timer = (callback) => {
setTimeout(() => {
callback()
},3000)
}
// timer.test.js
import { timer } from './timer'
jest.useFakeTimers();
test('timer 测试', () => {
const fn = jest.fn();
timer(fn);
jest.runAllTimers();
expect(fn).toHaveBeenCalledTimes(1);
})
二、runOnlyPendingTimers 运行只处于队列中任务
//timer
export const timer = (callback) => {
setTimeout(() => {
callback()
setTimeout(() => {
callback()
})
},3000)
}
//timer.test.js
import { timer } from './timer'
jest.useFakeTimers();
test('timer 测试', () => {
const fn = jest.fn();
timer(fn);
jest.runOnlyPendingTimers();
expect(fn).toHaveBeenCalledTimes(1);
})
三、advanceTimersByTime 时间快进
// timer.js
export const timer = (callback) => {
setTimeout(() => {
callback()
setTimeout(() => {
callback()
},3000)
},3000)
}
// timer.test.js
import { timer } from './timer'
jest.useFakeTimers();
test('timer 测试', () => {
const fn = jest.fn();
timer(fn);
jest.advanceTimersByTime(3000);
expect(fn).toHaveBeenCalledTimes(1);
})
四、排除各测试之间的干扰
import { timer } from './timer'
beforeEach(() => {
jest.useFakeTimers()
})
test('timer 测试', () => {
const fn = jest.fn();
timer(fn);
jest.advanceTimersByTime(3000);
expect(fn).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(3000);
expect(fn).toHaveBeenCalledTimes(2);
})
test('timer1 测试', () => {
const fn = jest.fn();
timer(fn);
jest.advanceTimersByTime(3000);
expect(fn).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(3000);
expect(fn).toHaveBeenCalledTimes(2);
})
网友评论