only 测试


¥only tests

如果 Node.js 以 --test-only 命令行选项启动,或者禁用测试隔离,则可以通过将 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() 中使用 subtests 时,需要使用 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.
  });
});