fix: advance fake timers with expect.poll interval (#10022) · vitest-dev/vitest@3f5bfa3 (original) (raw)
File tree
- packages/vitest/src/integrations/chai
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -3,6 +3,7 @@ import type { Test } from '@vitest/runner' | ||
| 3 | 3 | import { chai } from '@vitest/expect' |
| 4 | 4 | import { delay, getSafeTimers } from '@vitest/utils/timers' |
| 5 | 5 | import { getWorkerState } from '../../runtime/utils' |
| 6 | +import { vi } from '../vi' | |
| 6 | 7 | |
| 7 | 8 | // these matchers are not supported because they don't make sense with poll |
| 8 | 9 | const unsupported = [ |
| @@ -123,6 +124,9 @@ export function createExpectPoll(expect: ExpectStatic): ExpectStatic['poll'] { | ||
| 123 | 124 | } |
| 124 | 125 | |
| 125 | 126 | await delay(interval, setTimeout) |
| 127 | +if (vi.isFakeTimers()) { | |
| 128 | +vi.advanceTimersByTime(interval) | |
| 129 | +} | |
| 126 | 130 | } |
| 127 | 131 | } |
| 128 | 132 | } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -66,6 +66,21 @@ test('fake timers don\'t break it', async () => { | ||
| 66 | 66 | expect(diff >= 100).toBe(true) |
| 67 | 67 | }) |
| 68 | 68 | |
| 69 | +test('fake timers are advanced on each poll interval', async ({ onTestFinished }) => { | |
| 70 | +vi.useFakeTimers() | |
| 71 | +onTestFinished(() => { | |
| 72 | +vi.useRealTimers() | |
| 73 | +}) | |
| 74 | + | |
| 75 | +let didAdvance = false | |
| 76 | + | |
| 77 | +setTimeout(() => { | |
| 78 | +didAdvance = true | |
| 79 | +}, 50) | |
| 80 | + | |
| 81 | +await expect.poll(() => didAdvance, { interval: 100 }).toBe(true) | |
| 82 | +}) | |
| 83 | + | |
| 69 | 84 | test('custom matcher works correctly', async () => { |
| 70 | 85 | const fn = vi.fn() |
| 71 | 86 | let idx = 0 |