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
6 changes: 6 additions & 0 deletions docs/api/vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,12 @@ unmockedIncrement(30) === 31

The implementation is based internally on [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).

## vi.isFakeTimers

- **Type:** `() => boolean`
Dunqing marked this conversation as resolved.
Show resolved Hide resolved

Returns `true` if fake timers are enabled.

## vi.useRealTimers

- **Type:** `() => Vitest`
Expand Down
4 changes: 4 additions & 0 deletions packages/vitest/src/integrations/mock/timers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,10 @@ export class FakeTimers {
this._userConfig = config
}

isFakeTimers() {
return this._fakingTime
}

private _checkFakeTimers() {
if (!this._fakingTime) {
throw new Error(
Expand Down
5 changes: 5 additions & 0 deletions packages/vitest/src/integrations/vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { fn, isMockFunction, spies, spyOn } from './spy'
import { waitFor } from './wait'

interface VitestUtils {
isFakeTimers: () => boolean
Dunqing marked this conversation as resolved.
Show resolved Hide resolved
useFakeTimers(config?: FakeTimerInstallOpts): this
useRealTimers(): this
runOnlyPendingTimers(): this
Expand Down Expand Up @@ -215,6 +216,10 @@ function createVitest(): VitestUtils {
return utils
},

isFakeTimers() {
return _timers.isFakeTimers()
},

useRealTimers() {
_timers.useRealTimers()
_mockedDate = null
Expand Down
6 changes: 1 addition & 5 deletions packages/vitest/src/integrations/wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,8 @@ export function waitFor<T>(callback: WaitForCallback<T>, options: number | WaitF
}

const checkCallback = () => {
try {
// use fake timers
vi.getTimerCount()
if (vi.isFakeTimers())
vi.advanceTimersByTime(interval)
}
catch {}

if (promiseStatus === 'pending')
return
Expand Down