fakeRandom experimental 5.2.0+
- Type:
{ enableGlobally?: boolean }
Options for vi.useFakeRandom().
fakeRandom.enableGlobally
- Type:
boolean - Default:
false
Should Vitest automatically call vi.useFakeRandom() before it imports the setup files and the test file. Then Math.random, crypto and node:crypto return values from the seed option in the whole file, also in libraries that keep a reference to these functions when they load, such as lodash and uuid.
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
fakeRandom: {
enableGlobally: true,
},
},
})If a test calls vi.useRealRandom(), Vitest calls vi.useFakeRandom() again before the next test.
If the config does not set a seed, each run gets new values. For values that must be the same on every run, for example IDs in a snapshot, set seed in the config.
A module keeps the functions that it found when it loaded. So a module that kept the fake functions still returns seeded values after vi.useRealRandom(). A module that loaded before Vitest imported the setup files, for example in a custom environment, still returns real values. For other values that the fake cannot repeat, see vi.useFakeRandom.
This option cannot be used together with restoreRandom.
WARNING
Tests and hooks that run at the same time (see test.concurrent and sequence.hooks) share these functions, so their values would depend on the order of the calls. The fake functions throw an error in concurrent tests and suites, and in hooks that run at the same time. Use context.random in concurrent tests.