在我们的前端开发过程中,很多场景需要我们进行时间相关的操作,例如定时器、动画、网络请求等等。而在测试这些场景时,我们如何去模拟时间以便于进行测试呢?
Jest 的 fake timers 功能可以帮助我们模拟时间,并且提供了多种操作时间的方法,以便于我们进行测试。本文将会介绍 Jest 的 fake timers 功能,包括如何在 Jest 中使用 fake timers、常用的 fake timers 方法、以及在测试中使用 fake timers 的正确姿势。
如何在 Jest 中使用 fake timers
Jest 提供了全局的 jest.useFakeTimers 方法,可以帮助我们开启 fake timers 功能:
jest.useFakeTimers();
在执行该方法之后,所有的 timers 都会被 mock 掉,以便于我们在测试中进行模拟。
但是需要特别注意的是,我们需要在每一个测试用例结束之后,调用 jest.runOnlyPendingTimers 方法,手动触发所有等待触发的 timers,以便于我们进行断言:
// www.javascriptcn.com code example
it('测试定时器', () => {
jest.useFakeTimers();
const fn = jest.fn();
setInterval(fn, 1000);
expect(fn).not.toBeCalled();
jest.runOnlyPendingTimers();
expect(fn).toBeCalled();
});常用的 fake timers 方法
下面是 Jest 中常用的 fake timers 方法:
jest.advanceTimersByTime(ms)
让所有 timers 快进 ms 毫秒。用法如下:
// www.javascriptcn.com code example
it('测试定时器', () => {
jest.useFakeTimers();
const fn = jest.fn();
setTimeout(fn, 1000);
expect(fn).not.toBeCalled();
jest.advanceTimersByTime(1000);
expect(fn).toBeCalled();
});jest.runOnlyPendingTimers()
让系统触发待执行的 timers。用法见上文。
jest.runAllTimers()
让系统触发所有 timers。用法如下:
// www.javascriptcn.com code example
it('测试定时器', () => {
jest.useFakeTimers();
const fn = jest.fn();
setInterval(fn, 1000);
expect(fn).not.toBeCalled();
jest.runAllTimers();
expect(fn).toBeCalled();
});jest.getTimerCount()
获取现在还有多少个待执行的 timers。用法如下:
// www.javascriptcn.com code example
it('测试定时器', () => {
jest.useFakeTimers();
const fn = jest.fn();
setTimeout(fn, 1000);
expect(jest.getTimerCount()).toBe(1);
jest.advanceTimersByTime(1000);
expect(jest.getTimerCount()).toBe(0);
});在测试中使用 fake timers 的正确姿势
在实际的测试中,我们需要注意以下几点:
- fake timers 应该在每个测试用例中被开启和关闭;
- fake timers 应该在每个测试用例结束之后被重置;
- 每个测试用例应该首先调用 jest.useFakeTimers(),然后再执行测试。
下面是一个示例:
// www.javascriptcn.com code example
describe('测试定时器', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
jest.clearAllMocks();
jest.useRealTimers();
});
it('测试定时器', () => {
const fn = jest.fn();
setInterval(fn, 1000);
expect(fn).not.toBeCalled();
jest.runOnlyPendingTimers();
expect(fn).toBeCalled();
});
});小结
Jest 的 fake timers 功能为我们在测试时间相关场景时提供了非常方便的工具。本文介绍了 Jest 的 fake timers 功能的基本使用方法、常用的 fake timers 方法以及在测试中 fake timers 使用的正确姿势。希望读者们在今后的测试工作中,能够更加顺手地使用 Jest 的 fake timers 功能。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d62d6ba941bf7134bda3a4