计时器#
每当我们的测试代码涉及到 超时 或者间隔时,并不是让我们的测试程序进行等待或者超时。我们也可以通过模拟对 setTimeout 和 setInterval 的调用来使用 “假” 计时器来加速测试。
有关更深入的详细 API 描述,参阅 vi.usefaketimersapi 部分。
Vitest
示例
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'const executeAfterTwoHours = (func) => {setTimeout(func, 1000 * 60 * 60 * 2) // 2 hours}const executeEveryMinute = (func) => {setInterval(func, 1000 * 60) // 1 minute}const mock = vi.fn(() => console.log('executed'))describe('delayed execution', () => {beforeEach(() => {vi.useFakeTimers()})afterEach(() => {vi.restoreAllMocks()})it('should execute the function', () => {executeAfterTwoHours(mock)vi.runAllTimers()expect(mock).toHaveBeenCalledTimes(1)})it('should not execute the function', () => {executeAfterTwoHours(mock)// advancing by 2ms won't trigger the funcvi.advanceTimersByTime(2)expect(mock).not.toHaveBeenCalled()})it('should execute every minute', () => {executeEveryMinute(mock)vi.advanceTimersToNextTimer()expect(mock).toHaveBeenCalledTimes(1)vi.advanceTimersToNextTimer()expect(mock).toHaveBeenCalledTimes(2)})})
