Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(vitest): support vi.waitFor method #4113

Merged
merged 18 commits into from Sep 14, 2023
1 change: 1 addition & 0 deletions docs/api/vi.md
Expand Up @@ -775,3 +775,4 @@ test('Server started successfully', async () => {
})
```

If `vi.useFakeTimers` is used, `vi.waitFor` automatically calls `vi.AdvanceTimersByTime(interval)` in every check callback.
5 changes: 5 additions & 0 deletions packages/vitest/src/integrations/wait.ts
@@ -1,4 +1,5 @@
import { getSafeTimers } from '@vitest/utils'
import { vi } from './vi'

// The waitFor function was inspired by https://github.com/testing-library/web-testing-library/pull/2

Expand Down Expand Up @@ -52,6 +53,10 @@ export function waitFor<T>(callback: WaitForCallback<T>, options: number | WaitF
}

const checkCallback = () => {
// use fake timers
if (globalThis.setTimeout !== setTimeout)
Dunqing marked this conversation as resolved.
Show resolved Hide resolved
vi.advanceTimersByTime(interval)

if (promiseStatus === 'pending')
return
try {
Expand Down
7 changes: 2 additions & 5 deletions test/core/test/wait.test.ts
@@ -1,4 +1,3 @@
import { getSafeTimers } from '@vitest/utils'
import { describe, expect, test, vi } from 'vitest'

describe('waitFor', () => {
Expand Down Expand Up @@ -88,9 +87,7 @@ describe('waitFor', () => {
test('fakeTimer works', async () => {
vi.useFakeTimers()

const { setTimeout: safeSetTimeout } = getSafeTimers()

safeSetTimeout(() => {
setTimeout(() => {
vi.advanceTimersByTime(200)
}, 50)

Expand All @@ -100,7 +97,7 @@ describe('waitFor', () => {
resolve()
}, 150)
})
}, 50)
}, 200)

vi.useRealTimers()
})
Expand Down