随机化测试执行顺序
🌐 Randomizing tests execution order
测试运行器可以随机化执行顺序,以帮助检测依赖顺序的测试。启用后,运行器会随机化已发现的测试文件以及每个文件中的排队测试。使用 --test-randomize 来启用此模式。
🌐 The test runner can randomize execution order to help detect
order-dependent tests. When enabled, the runner randomizes both discovered
test files and queued tests within each file. Use --test-randomize to
enable this mode.
node --test --test-randomize 当启用随机化时,测试运行器会将用于此次运行的种子作为诊断信息打印出来:
🌐 When randomization is enabled, the test runner prints the seed used for the run as a diagnostic message:
Randomized test order seed: 12345 使用 --test-random-seed=<number> 可以以确定性的方式重放相同的随机顺序。提供 --test-random-seed 也会启用随机化,因此在提供种子时 --test-randomize 是可选的:
🌐 Use --test-random-seed=<number> to replay the same randomized order
deterministically. Supplying --test-random-seed also enables randomization,
so --test-randomize is optional when a seed is provided:
node --test --test-random-seed=12345 在大多数测试文件中,随机化会自动进行。一个重要的例外是当子测试一个接一个地被等待时。在这种模式下,每个子测试只有在前一个完成后才开始,因此运行器会保持声明顺序,而不是将其随机化。
🌐 In most test files, randomization works automatically. One important exception is when subtests are awaited one by one. In that pattern, each subtest starts only after the previous one finishes, so the runner keeps declaration order instead of randomizing it.
示例:这是顺序运行的,不是随机的。
🌐 Example: this runs sequentially and is not randomized.
import test from 'node:test';
test('math', async (t) => {
for (const name of ['adds', 'subtracts', 'multiplies']) {
// Sequentially awaiting each subtest preserves declaration order.
await t.test(name, async () => {});
}
});const test = require('node:test');
test('math', async (t) => {
for (const name of ['adds', 'subtracts', 'multiplies']) {
// Sequentially awaiting each subtest preserves declaration order.
await t.test(name, async () => {});
}
});使用套件式 API,例如 describe()/it() 或 suite()/test() 仍然允许随机化,因为同级测试会一起排队。
🌐 Using suite-style APIs such as describe()/it() or suite()/test()
still allows randomization, because sibling tests are enqueued together.
例如:这仍然符合随机分配的条件。
🌐 Example: this remains eligible for randomization.
import { describe, it } from 'node:test';
describe('math', () => {
it('adds', () => {});
it('subtracts', () => {});
it('multiplies', () => {});
});const { describe, it } = require('node:test');
describe('math', () => {
it('adds', () => {});
it('subtracts', () => {});
it('multiplies', () => {});
});--test-randomize 和 --test-random-seed 不支持 --watch 模式。
匹配的文件将作为测试文件执行。有关测试文件执行的更多信息,请参见测试运行器执行模型部分。
🌐 Matching files are executed as test files. More information on the test file execution can be found in the test runner execution model section.