context.workerId


运行当前测试文件的工作线程的唯一标识符。该值来源于 NODE_TEST_WORKER_ID 环境变量。在使用 --test-isolation=process(默认)运行测试时,每个测试文件在单独的子进程中运行,并被分配一个从 1 到 N 的工作线程 ID,其中 N 是并发工作线程的数量。在使用 --test-isolation=none 运行时,所有测试都在同一个进程中运行,工作线程 ID 始终为 1。当不在测试环境中运行时,该值为 undefined

🌐 The unique identifier of the worker running the current test file. This value is derived from the NODE_TEST_WORKER_ID environment variable. When running tests with --test-isolation=process (the default), each test file runs in a separate child process and is assigned a worker ID from 1 to N, where N is the number of concurrent workers. When running with --test-isolation=none, all tests run in the same process and the worker ID is always 1. This value is undefined when not running in a test context.

此属性用于在并发测试文件之间分配资源(如数据库连接或服务器端口):

🌐 This property is useful for splitting resources (like database connections or server ports) across concurrent test files:

import { test } from 'node:test';
import { process } from 'node:process';

test('database operations', async (t) => {
  // Worker ID is available via context
  console.log(`Running in worker ${t.workerId}`);

  // Or via environment variable (available at import time)
  const workerId = process.env.NODE_TEST_WORKER_ID;
  // Use workerId to allocate separate resources per worker
});