无关的异步活动


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

在下面的示例中,测试完成时仍然有两个 setImmediate() 操作未完成。 第一个 setImmediate() 尝试创建新的子测试。 因为父测试已经完成并输出结果,所以新的子测试立即标记为失败,稍后报告给 <TestsStream>

第二个 setImmediate() 创建了 uncaughtException 事件。 源自已完成测试的 uncaughtExceptionunhandledRejection 事件被 test 模块标记为失败,并由 <TestsStream> 在顶层报告为诊断警告。

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 results are reported 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 later to the <TestsStream>.

The second setImmediate() creates an uncaughtException event. uncaughtException and unhandledRejection events originating from a completed test are marked as failed by the test module and reported as diagnostic warnings at the top level by the <TestsStream>.

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.
});