计时器#

每当我们的测试代码涉及到 超时 或者间隔时,并不是让我们的测试程序进行等待或者超时。我们也可以通过模拟对 setTimeout 和 setInterval 的调用来使用 “假” 计时器来加速测试。
有关更深入的详细 API 描述,参阅 vi.usefaketimersapi 部分。
Vitest

示例

  1. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  2. const executeAfterTwoHours = (func) => {
  3. setTimeout(func, 1000 * 60 * 60 * 2) // 2 hours
  4. }
  5. const executeEveryMinute = (func) => {
  6. setInterval(func, 1000 * 60) // 1 minute
  7. }
  8. const mock = vi.fn(() => console.log('executed'))
  9. describe('delayed execution', () => {
  10. beforeEach(() => {
  11. vi.useFakeTimers()
  12. })
  13. afterEach(() => {
  14. vi.restoreAllMocks()
  15. })
  16. it('should execute the function', () => {
  17. executeAfterTwoHours(mock)
  18. vi.runAllTimers()
  19. expect(mock).toHaveBeenCalledTimes(1)
  20. })
  21. it('should not execute the function', () => {
  22. executeAfterTwoHours(mock)
  23. // advancing by 2ms won't trigger the func
  24. vi.advanceTimersByTime(2)
  25. expect(mock).not.toHaveBeenCalled()
  26. })
  27. it('should execute every minute', () => {
  28. executeEveryMinute(mock)
  29. vi.advanceTimersToNextTimer()
  30. expect(mock).toHaveBeenCalledTimes(1)
  31. vi.advanceTimersToNextTimer()
  32. expect(mock).toHaveBeenCalledTimes(2)
  33. })
  34. })