only 测试


如果 Node.js 使用 --test-only 命令行选项启动,则可以通过将 only 选项传给应该运行的测试来跳过除选定子集之外的所有顶层测试。 当运行带有 only 选项集的测试时,所有子测试也会运行。 测试上下文的 runOnly() 方法可用于在子测试级别实现相同的行为。

// 假设 Node.js 使用 --test-only 命令行选项运行。
// 设置了 'only' 选项,因此运行此测试。
test('this test is run', { only: true }, async (t) => {
  // 在此测试中,默认运行所有子测试。
  await t.test('running subtest');

  // 可以使用 'only' 选项更新测试上下文以运行子测试。
  t.runOnly(true);
  await t.test('this subtest is now skipped');
  await t.test('this subtest is run', { only: true });

  // 切换上下文以执行所有测试。
  t.runOnly(false);
  await t.test('this subtest is now run');

  // 显式地不要运行这些测试。
  await t.test('skipped subtest 3', { only: false });
  await t.test('skipped subtest 4', { skip: true });
});

// 未设置 'only' 选项,因此跳过此测试。
test('this test is not run', () => {
  // 此代码未运行。
  throw new Error('fail');
});

If Node.js is started with the --test-only command-line option, it is possible to skip all top level tests except for a selected subset by passing the only option to the tests that should be run. When a test with the only option set is run, all subtests are also run. The test context's runOnly() method can be used to implement the same behavior at the subtest level.

// Assume Node.js is run with the --test-only command-line option.
// The 'only' option is set, so this test is run.
test('this test is run', { only: true }, async (t) => {
  // Within this test, all subtests are run by default.
  await t.test('running subtest');

  // The test context can be updated to run subtests with the 'only' option.
  t.runOnly(true);
  await t.test('this subtest is now skipped');
  await t.test('this subtest is run', { only: true });

  // Switch the context back to execute all tests.
  t.runOnly(false);
  await t.test('this subtest is now run');

  // Explicitly do not run these tests.
  await t.test('skipped subtest 3', { only: false });
  await t.test('skipped subtest 4', { skip: true });
});

// The 'only' option is not set, so this test is skipped.
test('this test is not run', () => {
  // This code is not run.
  throw new Error('fail');
});