test([name][, options][, fn])


  • name <string> 测试的名称,在报告测试结果时显示。默认值: fnname 属性,或如果 fn 没有名称,则为 '<anonymous>'
  • options <Object> 测试的配置选项。支持以下属性:
    • concurrency <number> | <boolean> 如果提供了一个数字,则会有那么多测试同时运行。 如果为真值,则会以(CPU 核心数 - 1)的数量并行运行测试。 对于子测试,将会有 Infinity 个测试同时运行。 如果为假值,则一次只运行一个测试。 如果未指定,子测试将从其父测试继承此值。 默认值: false
    • only <boolean> 如果为真,并且测试环境配置为只运行 only 测试,则该测试将被执行。否则,该测试将被跳过。默认值: false
    • signal <AbortSignal> 允许中止正在进行的测试。
    • skip <boolean> | <string> 如果为真,则跳过测试。如果提供一个字符串,该字符串将在测试结果中显示,作为跳过测试的原因。默认值: false
    • todo <boolean> | <string> 如果为真,则将测试标记为 TODO。如果提供了一个字符串,该字符串将在测试结果中显示,作为该测试为 TODO 的原因。默认值: false
    • timeout <number> 测试将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值: Infinity
  • fn <Function> | <AsyncFunction> 被测试的函数。此函数的第一个参数是一个 TestContext 对象。如果测试使用回调函数,回调函数将作为第二个参数传入。默认值: 一个空操作函数。
  • 返回:<Promise> 在测试完成后以 undefined 解决。

test() 函数是从 test 模块导入的值。每次调用该函数都会在 TAP 输出中创建一个测试点。

【The test() function is the value imported from the test module. Each invocation of this function results in the creation of a test point in the TAP output.】

传递给 fn 参数的 TestContext 对象可用于执行与当前测试相关的操作。例如,包括跳过测试、添加额外的 TAP 诊断信息,或创建子测试。

【The TestContext object passed to the fn argument can be used to perform actions related to the current test. Examples include skipping the test, adding additional TAP diagnostic information, or creating subtests.】

test() 返回一个在测试完成时解决的 Promise。对于顶层测试,返回值通常可以忽略。然而,子测试的返回值应该被使用,以防止父测试先完成并取消子测试,如下面的示例所示。

test('top level test', async (t) => {
  // The setTimeout() in the following subtest would cause it to outlive its
  // parent test if 'await' is removed on the next line. Once the parent test
  // completes, it will cancel any outstanding subtests.
  await t.test('longer running subtest', async (t) => {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, 1000);
    });
  });
}); 

timeout 选项可用于在测试执行时间超过 timeout 毫秒时使其失败。然而,它并不是一个可靠的取消测试的机制,因为正在运行的测试可能会阻塞应用线程,从而阻止计划中的取消操作。

【The timeout option can be used to fail the test if it takes longer than timeout milliseconds to complete. However, it is not a reliable mechanism for canceling tests because a running test might block the application thread and thus prevent the scheduled cancellation.】