无关的异步活动


一旦测试函数完成执行,则 TAP 结果会尽快输出,同时保持测试的顺序。 但是,测试函数可能会生成比测试本身寿命更长的异步活动。 测试运行器处理此类活动,但不会延迟报告测试结果以适应它。

在下面的示例中,测试完成时仍然有两个 setImmediate() 操作未完成。 第一个 setImmediate() 尝试创建新的子测试。 因为父测试已经完成并输出结果,新的子测试立即被标记为失败,并在文件的 TAP 输出的顶层报告。

第二个 setImmediate() 创建了 uncaughtException 事件。 源自已完成测试的 uncaughtExceptionunhandledRejection 事件由 test 模块处理,并在文件的 TAP 输出的顶层报告为诊断警告。

test('a test that creates asynchronous activity', (t) => {
  setImmediate(() => {
    t.test('subtest that is created too late', (t) => {
      throw new Error('error1');
    });
  });

  setImmediate(() => {
    throw new Error('error2');
  });

  // 此行之后测试结束。
});

Once a test function finishes executing, the TAP results are output as quickly as possible while maintaining the order of the tests. However, it is possible for the test function to generate asynchronous activity that outlives the test itself. The test runner handles this type of activity, but does not delay the reporting of test results in order to accommodate it.

In the following example, a test completes with two setImmediate() operations still outstanding. The first setImmediate() attempts to create a new subtest. Because the parent test has already finished and output its results, the new subtest is immediately marked as failed, and reported in the top level of the file's TAP output.

The second setImmediate() creates an uncaughtException event. uncaughtException and unhandledRejection events originating from a completed test are handled by the test module and reported as diagnostic warnings in the top level of the file's TAP output.

test('a test that creates asynchronous activity', (t) => {
  setImmediate(() => {
    t.test('subtest that is created too late', (t) => {
      throw new Error('error1');
    });
  });

  setImmediate(() => {
    throw new Error('error2');
  });

  // The test finishes after this line.
});