only 测试


only tests】

如果使用 --test-only 命令行选项启动 Node.js,或者禁用了测试隔离,则可以通过将 only 选项传递给应运行的测试,从而跳过除所选子集之外的所有测试。当设置了 only 选项的测试时,其所有子测试也会运行。 如果测试套件设置了 only 选项,则套件中的所有测试都会运行,除非其子孙测试也设置了 only 选项,在这种情况下只有这些测试会运行。

【If Node.js is started with the --test-only command-line option, or test isolation is disabled, it is possible to skip all tests except for a selected subset by passing the only option to the tests that should run. When a test with the only option is set, all subtests are also run. If a suite has the only option set, all tests within the suite are run, unless it has descendants with the only option set, in which case only those tests are run.】

test()/it() 中使用 子测试 时,需要将所有父测试标记为 only 选项,以仅运行所选的测试子集。

【When using subtests within a test()/it(), it is required to mark all ancestor tests with the only option to run only a selected subset of tests.】

测试上下文的 runOnly() 方法可以用于在子测试层面实现相同的行为。未执行的测试将从测试运行器输出中省略。

【The test context's runOnly() method can be used to implement the same behavior at the subtest level. Tests that are not executed are omitted from the test runner output.】

// Assume Node.js is run with the --test-only command-line option.
// The suite's 'only' option is set, so these tests are 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');
});

describe('a suite', () => {
  // The 'only' option is set, so this test is run.
  it('this test is run', { only: true }, () => {
    // This code is run.
  });

  it('this test is not run', () => {
    // This code is not run.
    throw new Error('fail');
  });
});

describe.only('a suite', () => {
  // The 'only' option is set, so this test is run.
  it('this test is run', () => {
    // This code is run.
  });

  it('this test is run', () => {
    // This code is run.
  });
});