test([name][, options][, fn])
name<string> 测试的名称,在报告测试结果时显示。默认值:fn的name属性,或如果fn没有名称,则为'<anonymous>'。options<Object> 测试的配置选项。支持以下属性:concurrency<number> | <boolean> 如果提供了一个数字,那么应用线程中会有相应数量的测试并行运行。如果为true,所有计划的异步测试将在同一线程中同时运行。如果为false,一次只运行一个测试。如果未指定,子测试将继承父测试的该值。默认值:false。only<boolean> 如果为真,并且测试环境配置为只运行only测试,则该测试将被执行。否则,该测试将被跳过。默认值:false。signal<AbortSignal> 允许中止正在进行的测试。skip<boolean> | <string> 如果为真,则跳过测试。如果提供一个字符串,该字符串将在测试结果中显示,作为跳过测试的原因。默认值:false。todo<boolean> | <string> 如果为真,则将测试标记为TODO。如果提供了一个字符串,该字符串将在测试结果中显示,作为该测试为TODO的原因。默认值:false。timeout<number> 测试将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值:Infinity。plan<number> 预计在测试中运行的断言和子测试的数量。如果测试中运行的断言数量与计划中指定的数量不匹配,测试将失败。 默认值:undefined.
fn<Function> | <AsyncFunction> 被测试的函数。此函数的第一个参数是一个TestContext对象。如果测试使用回调函数,回调函数将作为第二个参数传入。默认值: 一个空操作函数。- 返回:<Promise> 测试完成后会以
undefined作为结果被解决,或者如果测试在一个套件中运行,则会立即解决。
test() 函数是从 test 模块导入的值。每次调用此函数都会将测试结果报告给 <TestsStream>。
【The test() function is the value imported from the test module. Each
invocation of this function results in reporting the test to the <TestsStream>.】
传递给 fn 参数的 TestContext 对象可以用于执行与当前测试相关的操作。示例包括跳过测试、添加额外的诊断信息或创建子测试。
【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 diagnostic information, or creating subtests.】
test() 会返回一个在测试完成后执行的 Promise。
如果在一个测试套件中调用 test(),它会立即完成。
对于顶层测试,通常可以忽略返回值。
然而,对于子测试,应该使用返回值以防止父测试先结束并取消子测试,
如下例所示。
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.】