Skip to content

feat(experimental): add vi.useFakeRandom and restoreRandom - #11933

Open
sheremet-va wants to merge 1 commit into
feat/seed-randomfrom
feat/fake-random
Open

sheremet-va wants to merge 1 commit into
feat/seed-randomfrom
feat/fake-random

Conversation

@sheremet-va

@sheremet-va sheremet-va commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Stacked on #11930. Contains the commit of #11956 until it merges.

Adds experimental vi.useFakeRandom(), vi.useRealRandom() and vi.isFakeRandom(). They replace Math.random, crypto.getRandomValues, crypto.randomUUID and, in Node.js, randomBytes, randomFill, randomFillSync, randomInt and randomUUID of node:crypto (also named imports) with functions that return values from the seed option.

  • In a test, its hooks and its test fixtures, the values are those of context.random.fork('vitest:globals'), so a test keeps its values when tests are filtered or shuffled, and each retry starts again. beforeAll, afterAll and aroundAll use a seed of the suite, fixtures of file or worker scope use a seed of the fixture, and other code uses a seed of the file.
  • The fakes throw an error in concurrent tests and suites, and in hooks that run at the same time (sequence.hooks: 'parallel').
  • The fakes call the real functions first, so invalid arguments and unbound calls throw the errors of Node.js and callbacks run at the same time. The values are taken when the function is called, not in the callback.
  • fakeRandom: { enableGlobally: true } calls vi.useFakeRandom() before the setup files and the test file load, and again before each test if a test restored the functions. Libraries that keep a reference when they load need it (lodash keeps Math.random, uuid keeps randomUUID).
  • restoreRandom: true calls vi.useRealRandom() before each test, like restoreMocks. It cannot be used together with fakeRandom.enableGlobally.
  • Each run has a new seed, so values that must be stable (for example IDs in snapshots) need seed in the config.

Not covered (documented): libraries that keep random bytes in a pool (nanoid, uuid), values that OpenSSL creates (key generation, some signatures), and other realms (workers, child processes, iframes).

@sheremet-va
sheremet-va added this pull request to stack #11934 November 10, 2026 12:57
@netlify

netlify Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for vitest-dev ready!

Name Link
🔨 Latest commit e5c70df
🔍 Latest deploy log https://app.netlify.com/projects/vitest-dev/deploys/6b06bb64e73f312812fbada0
😎 Deploy Preview https://deploy-preview-11933--vitest-dev.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@flakiness-io

flakiness-io Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Test Results Summary

This comment shows the latest test results for this pull request.

Commit Status Test Results CI Runs
e5c70df ✅ Passed 33064 passed · 239 flaky · 1197 skipped 30 runs
⚠️ 239 flaky

⚠️ win 10.0.26100 · vmThreads test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ Ubuntu 26.04 · vmThreads test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ Ubuntu 26.04 · threads test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ win 10.0.26100 · forks test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ Ubuntu 26.04 · vmThreads test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ win 10.0.26100 · threads test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ Ubuntu 26.04 · forks test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ Ubuntu 26.04 · forks test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ Ubuntu 26.04 · threads test/unit/test/retry.test.ts:55 › describe object add(1, 1) › returned value not be greater than 2
⚠️ win 10.0.26100 · vmThreads test/unit/test/retry.test.ts:61 › describe object add(1, 1) › returned value not be less than 2
…and 229 more

View full report

ℹ️ About Flakiness.io in GitHub

Your team has set up Flakiness.io pull request comments. This comment is updated when

  • The first test results arrive for this pull request
  • A later run reports more results for the same commit
  • A new commit is pushed and tested

Flakiness.io rewrites the comment in place, so it always reflects the most recently tested commit.

@sheremet-va sheremet-va changed the title feat: add vi.useFakeRandom and restoreRandom feat(experimental): add vi.useFakeRandom and restoreRandom Nov 10, 2026
@sheremet-va
sheremet-va force-pushed the feat/fake-random branch 3 times, most recently from d249277 to a362950 Compare November 13, 2026 13:39
AriPerkkio
AriPerkkio previously approved these changes Nov 15, 2026
Comment thread docs/api/vi.md

- Values from libraries that keep random bytes in a pool, such as `nanoid` and `uuid`. They use the bytes of earlier calls first, so the values of a test depend on the tests before it in the same file.
- Keys, signatures and other values that OpenSSL creates in `node:crypto` and `crypto.subtle`. Load keys from fixed data in a fixture instead.
- Values in workers, child processes and iframes. They have their own random functions.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably doesn't need to be called out. We don't mention it in mocking guide either.

Suggested change
- Values in workers, child processes and iframes. They have their own random functions.

macarie
macarie previously approved these changes Nov 16, 2026
Comment on lines +34 to +35
// `vi.useFakeRandom()` replaces `Math.random`
const random = Math.random

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think it would it make sense to move packages/spy/src/primordials.ts to the utils package and import from it as needed?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, probably

@sheremet-va
sheremet-va dismissed stale reviews from macarie and AriPerkkio via f1c7c11 November 18, 2026 12:14
@sheremet-va
sheremet-va force-pushed the feat/fake-random branch 4 times, most recently from a29810a to e53cb78 Compare November 24, 2026 20:38
Comment thread docs/api/random.md
- [`vi.createRandom`](/api/vi#vi-createrandom) in code without a test context, such as suite hooks, fixtures of file or worker scope, and setup files.
- [`project.createRandom`](/api/advanced/test-project#createrandom) in a [global setup file](/config/globalsetup).

For code that calls `Math.random()` or `crypto.randomUUID()`, use [`vi.useFakeRandom`](/api/vi#vi-usefakerandom).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, the doc narrative reads abrupt and terse. Some wording suggestions:

For code that calls builtin random APIs such as Math.random() or crypto.randomUUID(), use vi.useFakeRandom so that the functions returns random values based on same seed option.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't review docs yet, they are too AI slopped (in any PR). I gave up on them because with every change it would add new statements to docs and make it sound worse. I want to go over them after everything is done

Comment thread docs/config/restorerandom.md Resolved
Comment thread docs/api/test.md Outdated

- **Type:** `boolean`

`true` runs the test with the fake functions of [`vi.useFakeRandom()`](/api/vi#vi-usefakerandom), so `Math.random` and the random functions of `crypto` return values from the [seed](/config/seed) of the test. After the test, Vitest restores the functions that the test started with:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I realized this API doesn't seem to cover the code inside aroundEach since aroundEach itself wraps onBeforeTryTask. Probably it's not actionable but mentioning it since the doc's phrasing true runs the test with the fake functions leaving this vague.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should cover aroundEach, I think. If it doesn't it's a bug

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, this doesn't look intended and this has pre-existed for a long time (also affects like traceTimeline and mock reset too). This can be probably addressed separately from random PR.

@sheremet-va sheremet-va Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm gonna fix the seed use case only in this PR by not using onBeforeTryTask

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants