vitest icon indicating copy to clipboard operation
vitest copied to clipboard

Add async method variants from sinonjs/fake-timers to vitest

Open dkulchenko opened this issue 3 years ago • 0 comments

Clear and concise description of the problem

fake-timers provides an await clock.runAllAsync() call as an alternative to clock.runAll() (https://github.com/sinonjs/fake-timers#clockrunall--await-clockrunallasync) which makes it significantly easier to run all timers in a more complex asynchronous context (e.g. timers called by promises that are called by timers). Without it, it can be really difficult to actually have all timers run when those timers are initiated by other promises.

See Stack Overflow discussions such as https://stackoverflow.com/questions/51126786/jest-fake-timers-with-promises and https://stackoverflow.com/questions/52177631/jest-timer-and-promise-dont-work-well-settimeout-and-async-function to see scenarios where this is an issue.

For a similar reason, await clock.tickAsync, await clock.nextAsync, await clock.runToLastAsync would ideally also be exposed in some way.

I'm currently having to import sinon-js/fake-timers manually to provide this functionality, and I'd prefer to stay within vitest, especially since it's using fake-timers under the hood.

Suggested solution

Adding something like:

runAllTimersAsync(): Promise<void> {
    if (this._checkFakeTimers())
      this._clock.runAllAsync()
}

to packages/vitest/src/integrations/mock/timers.ts for each associated method (and tests as needed).

Alternative

No response

Additional context

No response

Validations

dkulchenko avatar Aug 05 '22 21:08 dkulchenko