Seeded Tests experimental 5.2.0+
A seeded test gets all of its random values from a seed. Vitest can repeat the test with other seeds to find the values that make it fail, and run 1 seed again to debug the failure. This is a small form of deterministic simulation testing: the test controls the random parts of a system, for example the order of network messages, and checks the result for many orders.
Random Values from a Seed
Each test has its own random source, context.random. Its seed comes from the seed option of the run, the project, the file, and the names of the test and its suites. If you do not set the seed option, each run gets a new seed, so the test checks new values on every run. A run with the same seed gets the same values:
import { expect, test } from 'vitest'
test('the queue keeps the order of messages', async ({ random }) => {
const queue = new Queue()
const messages = random.sample(['create', 'update', 'delete', 'archive'], 3)
for (const message of messages) {
await queue.push(message, { delay: random.int(0, 50) })
}
expect(await queue.drain()).toEqual(messages)
})If your code calls Math.random() or crypto.randomUUID(), use vi.useFakeRandom. Then these functions also return values from the seed of the test.
Repeat a Test with Other Seeds
The repeats option runs the test again, and each repeat gets its own seed. Thus context.random and vi.useFakeRandom give other values in each repeat:
import { expect, test } from 'vitest'
import { Cluster } from '../src/cluster'
import { SimulatedNetwork } from './simulated-network'
test('one leader per term', { repeats: 199 }, async ({ random }) => {
const network = new SimulatedNetwork(random.fork('network'))
const cluster = new Cluster({ nodes: 5, network })
await cluster.run({ steps: 1_000 })
expect(cluster.leadersPerTerm()).toBe(1)
})repeats: 199 runs the test 200 times. Each repeat is a full run of the test: beforeEach, afterEach, aroundEach and fixtures of test scope run again for each repeat. beforeAll, afterAll, aroundAll and fixtures of file and worker scope run only 1 time, so all repeats share them.
All repeats run, also after a repeat fails. If a repeat calls skip(), Vitest skips only this repeat. The test is skipped only if all of its repeats are skipped.
The first run has the same values as the test without repeats. Seeds that you keep in seeds run before it.
Replay a Seed
When a repeat that used its seed fails, Vitest prints a command after the error that runs the test again with this seed:
FAIL src/raft.test.ts > log entries are never lost
AssertionError: expected [ 1, 2, 4 ] to deeply equal [ 1, 2, 3, 4 ]
❯ src/raft.test.ts:12:31
Failed 1 of 200 runs
Replay vitest run src/raft.test.ts -t '^log entries are never lost$' --seed 158412337095872 --replay-seed 3fa2c9e1b07d5a44The command runs the test 1 time with this seed, so you can debug the failure, for example with a debugger or with more logs. Vitest prints it for any failed test that used context.random or vi.useFakeRandom, also without repeats.
The command also has the --seed of the run, because values outside the test, for example in beforeAll hooks or fixtures of file scope, come from it.
Many Failed Seeds
Often many seeds fail at the same place, with other values in the error message. Vitest shows these seeds in 1 block, with 1 error and 1 replay command:
FAIL src/raft.test.ts > log entries are never lost
AssertionError: expected [ 1, 2, 4 ] to deeply equal [ 1, 2, 3, 4 ]
❯ src/raft.test.ts:12:31
Failed 4 of 200 runs
Replay vitest run src/raft.test.ts -t '^log entries are never lost$' --seed 158412337095872 --replay-seed 3fa2c9e1b07d5a44The error and the replay command come from 1 of the seeds. A failure at another place gets its own block. All seeds are in the reports.
Reproduced or Not
When a repeat fails with its seed, Vitest runs it 1 more time and compares the errors. A seed that timed out does not run again, because the run could take the full timeout again. This second run is the replay. If the replay fails with the same error, Vitest prints nothing more. If not, the test depends on more than its seed, and Vitest prints a yellow line:
Reproduced no, the replay passed, so the test depends on more than its seed: the replay passed, was skipped, or failed with another error. The next line shows the other error.Reproduced no for 1 of 4 seeds (0e1d2c3b4a596877), so the test depends on more than its seeds: a block with more than 1 seed names the seeds that did not fail again.
The replay does not change the result of the test. With retry, the retries take its place, and a retry that passes makes the test flaky instead of failed.
The replay happens in the same process, right after the failure, so it shares the state of the module with the failed run. Thus a failure that repeats does not prove that the replay command fails, because the command runs only this test.
If the failure does not repeat, look for these causes:
- State that one run leaves for the next, for example a module variable, a cache, or data in a database. Reset it in
beforeEach, or create it in a fixture of test scope. - Random values that do not come from the seed. Use
context.random, orvi.useFakeRandomforMath.random()andcrypto. - Real time. Use the
fakeTimerstest option forsetTimeoutandDate, with anowrange or a fixednow.
Seeds in Reports
The reports show the same seeds and replay commands as the terminal:
- JSON:
failedSeedsof a test lists each failed seed with itsrepeatIndex, the index of its error infailureMessages(failureIndex), itsruns, the count of runs that failed with the same error (reproducedRuns), and itscommand.runSeedis the run seed. - JUnit: a
vitest.seedproperty for each failed seed, avitest.runSeedproperty of the test suite, and the seed details at the end of the first<failure>of each place where the test failed. - TAP:
# failed,# reproducedand# replaycomments after the first error of each place where the test failed. - GitHub Actions: 1 annotation with the seed details for the seeds that fail at the same place, and a "Failed Seeds" section in the job summary with the replay command of each place where a test failed.
- Vitest UI and the HTML report: the dashboard shows the run seed, and the report of a test shows its errors in the same groups as the terminal, with the seed details, the runs and all seeds of each error, and a button that copies the replay command. The trace view shows the seed of each attempt.
In a merged report, the replay command of a test has the flags and the seed of the run that tested its file.
Keep the Seeds That Failed
Each run gets a new run seed, so a seed that failed in CI does not run again by itself. After you fix the bug, add the seed to the seeds option. These seeds run before the repeats, so the test checks the old failure on every run. Each seed adds 1 run, and each seed can be in the list only 1 time. If a kept seed fails again, the Failed line names it, for example Failed 1 of 201 runs: kept seed 3fa2c9e1b07d5a44:
test('log entries are never lost', {
repeats: 199,
seeds: ['3fa2c9e1b07d5a44'],
}, async ({ random }) => {
// ...
})seeds does not set the count of repeats. A test with seeds and without repeats gets its repeats from a tag, the config or the --repeats flag, as in More Repeats in CI.
The seed of a test changes if you rename the test, move it to another file or suite, or change the run seed. A seed in seeds does not change, but after changes to the code it can test another path.
More Repeats in CI
The repeats option of the config and the --repeats flag set the repeats of tests that do not set repeats themselves. To run more repeats of the simulation tests in a nightly job, set repeats on a tag instead of on the tests:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
tags: [
{ name: 'simulation', repeats: process.env.NIGHTLY ? 1999 : 99 },
],
},
})Each run tests new seeds, because each run gets a new run seed. Vitest prints the run seed in the summary, and the replay command contains it. If you set the commit hash as the seed, a rerun of the CI job tests the same seeds, so a failure does not go away on a rerun. See Seeds in CI:
NIGHTLY=1 vitest run --tags-filter simulation --seed "$GITHUB_SHA"If the config sets seed, each run tests the same seeds. To test new seeds in a nightly job, use --seed random.
Find Flaky Tests
To check that all tests are stable, run every test many times:
vitest run --repeats 99Each repeat of a test that uses context.random or vi.useFakeRandom gets other random values. Other tests run as before. The Reproduced line shows if a failure does not repeat with the same seed.
Inject Faults
A simulation finds more bugs if the random values also control faults, for example lost or late messages. Give the code a dependency that gets its decisions from a fork of context.random, and use the real dependency in production:
import type { RandomSource } from 'vitest'
export class SimulatedNetwork implements Network {
private queue: Message[] = []
constructor(private random: RandomSource) {}
send(message: Message): void {
// lose 1% of the messages
if (this.random.bool(0.01)) {
return
}
this.queue.push(message)
}
// deliver the messages in a random order
receive(): Message | undefined {
if (!this.queue.length) {
return undefined
}
return this.queue.splice(this.random.int(0, this.queue.length - 1), 1)[0]
}
}Each part of the simulation gets its own fork, for example random.fork('network') and random.fork('disk'). Then a change in one part does not change the values of the other parts.
Fake Timers
A test that waits for real timers is slow, and a test that reads the real date can pass today and fail on the last day of the month. The fakeTimers test option gives each run of the test its own fake clock. With a now range, the clock starts at a time from the seed of the test. Thus each repeat tests another date, and the replay command of a failure starts at the same date on any day:
test('a subscription renews in the next month', {
repeats: 100,
fakeTimers: {
now: { min: new Date('2024-01-01'), max: new Date('2027-12-31') },
},
}, () => {
const subscription = subscribe()
vi.advanceTimersByTime(31 * DAY)
expect(subscription.invoices).toHaveLength(2)
})Use a range that agrees with the dates in your test data. For code that calls Math.random() or crypto, add the fakeRandom test option.
TIP
To give all simulation tests the same options, define a tag:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
tags: [
{
name: 'simulation',
repeats: 100,
fakeRandom: true,
fakeTimers: {
now: { min: new Date('2024-01-01'), max: new Date('2027-12-31') },
},
},
],
},
})test('a subscription renews in the next month', { tags: 'simulation' }, () => {
// ...
})Limits
- The seed controls only the random values and the start time of fake timers with a
nowrange. Real timers, I/O, other workers and the order of promises that wait for them can still change the result. - Only the values of the test change between repeats:
context.randomin the test, itsbeforeEachandafterEachhooks and its fixtures of test scope, andvi.useFakeRandomwhile the test runs.vi.createRandom,beforeAllhooks, fixtures of file and worker scope, and fake values that a module takes when it loads are the same for every repeat. - The
--repeatsflag does not change a test that setsrepeatsitself. Use a tag for the count, as in More Repeats in CI. - With
retry, a repeat that fails and then passes counts as passed. If you want every failure of a repeat to fail the test, do not setretryon these tests. - Each project gets other seeds. In browser mode, each browser instance is a separate project.
vi.useFakeRandomthrows an error in concurrent tests, because the tests shareMath.random. Usecontext.randomin concurrent tests.- Without a
nowoption, fake timers start at the real time. A failure that depends on the date can then pass when you run the replay command on another day. - The
fakeTimersandfakeRandomtest options throw an error for concurrent tests, because the tests share the timers and the random functions.