- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v16.20.2 文档
- Node.js v16.20.2
-
目录
- 测试运行器
- 子测试
- 跳过测试
describe/it语法- 无关的异步活动
- 从命令行运行测试
run([options])test([name][, options][, fn])describe([name][, options][, fn])describe.skip([name][, options][, fn])describe.todo([name][, options][, fn])it([name][, options][, fn])it.skip([name][, options][, fn])it.todo([name][, options][, fn])before([, fn][, options])after([, fn][, options])beforeEach([, fn][, options])afterEach([, fn][, options])- 类:
TapStream - 类:
TestContext - 类:
SuiteContext
- 测试运行器
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- 其他版本
测试运行器#>
【Test runner】
源代码: lib/test.js
node:test 模块便于创建以 轻拍 格式报告结果的 JavaScript 测试。访问方法如下:
【The node:test module facilitates the creation of JavaScript tests that
report results in TAP format. To access it:】
import test from 'node:test';const test = require('node:test');
此模块仅在 node: 方案下可用。以下用法将无法工作:
【This module is only available under the node: scheme. The following will not
work:】
import test from 'test';const test = require('test');
通过 test 模块创建的测试由单个函数组成,该函数可以通过三种方式之一进行处理:
【Tests created via the test module consist of a single function that is
processed in one of three ways:】
- 如果同步函数抛出异常则被视为失败,否则被视为通过。
- 一个返回
Promise的函数,如果Promise被拒绝则被视为失败,如果Promise被解决则被视为成功。 - 一个接收回调函数的函数。如果回调的第一个参数接收到任何真值,则测试被视为失败。如果第一个参数传递的是假值,则测试被视为通过。如果测试函数既接收回调函数又返回一个
Promise,测试将会失败。
以下示例说明了如何使用 test 模块编写测试。
【The following example illustrates how tests are written using the
test module.】
test('synchronous passing test', (t) => {
// This test passes because it does not throw an exception.
assert.strictEqual(1, 1);
});
test('synchronous failing test', (t) => {
// This test fails because it throws an exception.
assert.strictEqual(1, 2);
});
test('asynchronous passing test', async (t) => {
// This test passes because the Promise returned by the async
// function is not rejected.
assert.strictEqual(1, 1);
});
test('asynchronous failing test', async (t) => {
// This test fails because the Promise returned by the async
// function is rejected.
assert.strictEqual(1, 2);
});
test('failing test using Promises', (t) => {
// Promises can be used directly as well.
return new Promise((resolve, reject) => {
setImmediate(() => {
reject(new Error('this will cause the test to fail'));
});
});
});
test('callback passing test', (t, done) => {
// done() is the callback function. When the setImmediate() runs, it invokes
// done() with no arguments.
setImmediate(done);
});
test('callback failing test', (t, done) => {
// When the setImmediate() runs, done() is invoked with an Error object and
// the test fails.
setImmediate(() => {
done(new Error('callback failure'));
});
});
当测试文件执行时,TAP 会写入 Node.js 进程的标准输出。任何理解 TAP 格式的测试框架都可以解释此输出。如果有任何测试失败,进程退出码会被设置为 1。
【As a test file executes, TAP is written to the standard output of the Node.js
process. This output can be interpreted by any test harness that understands
the TAP format. If any tests fail, the process exit code is set to 1.】
子测试#>
【Subtests】
测试上下文的 test() 方法允许创建子测试。该方法的行为与顶层 test() 函数完全相同。下面的示例演示了如何创建一个包含两个子测试的顶层测试。
【The test context's test() method allows subtests to be created. This method
behaves identically to the top level test() function. The following example
demonstrates the creation of a top level test with two subtests.】
test('top level test', async (t) => {
await t.test('subtest 1', (t) => {
assert.strictEqual(1, 1);
});
await t.test('subtest 2', (t) => {
assert.strictEqual(2, 2);
});
});
在此示例中,使用 await 来确保两个子测试都已完成。这是必要的,因为父测试不会等待其子测试完成。任何在父测试结束时仍未完成的子测试都会被取消并视为失败。任何子测试失败都会导致父测试失败。
【In this example, await is used to ensure that both subtests have completed.
This is necessary because parent tests do not wait for their subtests to
complete. Any subtests that are still outstanding when their parent finishes
are cancelled and treated as failures. Any subtest failures cause the parent
test to fail.】
跳过测试#>
【Skipping tests】
可以通过向测试传递 skip 选项,或调用测试上下文的 skip() 方法来跳过单个测试。这两种方法都支持包含一条消息,该消息会在 TAP 输出中显示,如以下示例所示。
【Individual tests can be skipped by passing the skip option to the test, or by
calling the test context's skip() method. Both of these options support
including a message that is displayed in the TAP output as shown in the
following example.】
// The skip option is used, but no message is provided.
test('skip option', { skip: true }, (t) => {
// This code is never executed.
});
// The skip option is used, and a message is provided.
test('skip option with message', { skip: 'this is skipped' }, (t) => {
// This code is never executed.
});
test('skip() method', (t) => {
// Make sure to return here as well if the test contains additional logic.
t.skip();
});
test('skip() method with message', (t) => {
// Make sure to return here as well if the test contains additional logic.
t.skip('this is skipped');
});
describe/it 语法#>
【describe/it syntax】
运行测试也可以使用 describe 来声明一个测试套件,使用 it 来声明一个测试。测试套件用于组织和分组相关的测试。it 是 test 的别名,但不会传入测试上下文,因为嵌套是通过测试套件来实现的。
【Running tests can also be done using describe to declare a suite
and it to declare a test.
A suite is used to organize and group related tests together.
it is an alias for test, except there is no test context passed,
since nesting is done using suites.】
describe('A thing', () => {
it('should work', () => {
assert.strictEqual(1, 1);
});
it('should be ok', () => {
assert.strictEqual(2, 2);
});
describe('a nested thing', () => {
it('should work', () => {
assert.strictEqual(3, 3);
});
});
});
describe 和 it 是从 node:test 模块中导入的。
import { describe, it } from 'node:test';const { describe, it } = require('node:test');
only 测试#>
【only tests】
如果使用 --test-only 命令行选项启动 Node.js,可以通过向应运行的测试传递 only 选项来跳过所有顶层测试,除了选定的子集。当运行设置了 only 选项的测试时,所有子测试也会运行。测试上下文的 runOnly() 方法可以用于在子测试级别实现相同的行为。
【If Node.js is started with the --test-only command-line option, it is
possible to skip all top level tests except for a selected subset by passing
the only option to the tests that should be run. When a test with the only
option set is run, all subtests are also run. The test context's runOnly()
method can be used to implement the same behavior at the subtest level.】
// Assume Node.js is run with the --test-only command-line option.
// The 'only' option is set, so this test is 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');
});
无关的异步活动#>
【Extraneous asynchronous activity】
一旦测试函数执行完成,TAP 结果会尽快输出,同时保持测试顺序。然而,测试函数可能会产生超出测试自身生命周期的异步活动。测试运行器会处理这种类型的活动,但不会为了配合这些活动而延迟测试结果的报告。
【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.】
在以下示例中,一个测试在还有两个 setImmediate() 操作未完成的情况下就完成了。第一个 setImmediate() 尝试创建一个新的子测试。由于父测试已经完成并输出了结果,新子测试会立即被标记为失败,并在文件的顶层 TAP 输出中报告。
【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.】
第二个 setImmediate() 会触发 uncaughtException 事件。来自已完成测试的 uncaughtException 和 unhandledRejection 事件由 test 模块处理,并在文件 TAP 输出的顶层作为诊断警告报告。
【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.
});
从命令行运行测试#>
【Running tests from the command line】
可以通过在命令行传递 --test 标志来调用 Node.js 测试运行器:
【The Node.js test runner can be invoked from the command line by passing the
--test flag:】
node --test
默认情况下,Node.js 会递归搜索当前目录中符合特定命名约定的 JavaScript 源文件。匹配的文件会作为测试文件执行。有关预期测试文件命名约定和行为的更多信息,可以参见 测试运行器执行模型 部分。
【By default, Node.js will recursively search the current directory for JavaScript source files matching a specific naming convention. Matching files are executed as test files. More information on the expected test file naming convention and behavior can be found in the test runner execution model section.】
或者,可以将一个或多个路径作为 Node.js 命令的最终参数提供,如下所示。
【Alternatively, one or more paths can be provided as the final argument(s) to the Node.js command, as shown below.】
node --test test1.js test2.mjs custom_test_dir/
在这个例子中,测试运行器将执行文件 test1.js 和 test2.mjs。测试运行器还会递归地搜索 custom_test_dir/ 目录以查找要执行的测试文件。
【In this example, the test runner will execute the files test1.js and
test2.mjs. The test runner will also recursively search the
custom_test_dir/ directory for test files to execute.】
测试运行器执行模型#>
【Test runner execution model】
当搜索要执行的测试文件时,测试运行器的行为如下:
【When searching for test files to execute, the test runner behaves as follows:】
- 用户明确提供的任何文件都会被执行。
- 如果用户没有明确指定任何路径,将按照以下步骤在当前工作目录中递归搜索文件。
- 除非用户明确提供,否则会跳过
node_modules目录。 - 如果遇到名为
test的目录,测试运行器将递归搜索其中的所有.js、.cjs和.mjs文件。所有这些文件都会被视为测试文件,不需要符合下面详细说明的特定命名约定。这是为了适应将所有测试放在单个test目录中的项目。 - 在所有其他目录中,匹配以下模式的
.js、.cjs和.mjs文件被视为测试文件:^test$- 基名为字符串'test'的文件。例如:test.js、test.cjs、test.mjs。^test-.+- 文件名以字符串'test-'开头,后跟一个或多个字符。例如:test-example.js、test-another-example.mjs。.+[\.\-\_]test$- 文件名以.test、-test或_test结尾,前面有一个或多个字符。例如:example.test.js、example-test.cjs、example_test.mjs。- Node.js 能识别的其他文件类型,如
.node和.json,不会被测试运行器自动执行,但如果在命令行中明确提供,则是支持的。
每个匹配的测试文件都在单独的子进程中执行。如果子进程以退出码 0 结束,则该测试被视为通过。否则,测试被视为失败。测试文件必须可以被 Node.js 执行,但不要求内部使用 node:test 模块。
【Each matching test file is executed in a separate child process. If the child
process finishes with an exit code of 0, the test is considered passing.
Otherwise, the test is considered to be a failure. Test files must be
executable by Node.js, but are not required to use the node:test module
internally.】
run([options])#>
options<Object> 运行测试的配置选项。支持以下属性:concurrency<number> | <boolean> 如果提供了一个数字,那么将会有相应数量的文件并行运行。如果为真,则会运行(CPU 核心数 - 1)个文件并行运行。如果为假,则一次仅运行一个文件。如果未指定,子测试将继承其父测试的此值。默认值:true。files:<Array> 包含要运行的文件列表的数组。 默认 从 测试运行器执行模型 匹配的文件。signal<AbortSignal> 允许中止正在进行的测试执行。timeout<number> 测试执行将在指定的毫秒数后失败。如果未指定,子测试将继承其父测试的该值。默认值:Infinity。inspectPort<number> | <Function> 设置测试子进程的调试端口。可以是一个数字,也可以是一个不带参数且返回数字的函数。如果提供的是空值,每个进程将使用自己的端口,从主进程的process.debugPort开始递增。默认值:undefined。
- 返回:<TapStream>
run({ files: [path.resolve('./tests/test.js')] })
.pipe(process.stdout);
test([name][, options][, fn])#>
name<string> 测试的名称,在报告测试结果时显示。默认值:fn的name属性,或如果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.】
describe([name][, options][, fn])#>
name<string> 测试套件的名称,在报告测试结果时显示。默认值: 如果fn有名称,则为fn的name属性;如果fn没有名称,则为'<anonymous>'。options<Object> 套件的配置选项。支持与test([名称][, options][, fn])相同的选项。fn<Function> | <AsyncFunction> 套件下的函数,用于声明所有子测试和子套件。该函数的第一个参数是一个SuiteContext对象。默认值: 一个空操作函数。- 返回:
undefined。
从 node:test 模块导入的 describe() 函数。每次调用此函数都会创建一个子测试以及 TAP 输出中的一个测试点。在调用顶层 describe 函数后,所有顶层测试和测试套件将会执行。
【The describe() function imported from the node:test module. Each
invocation of this function results in the creation of a Subtest
and a test point in the TAP output.
After invocation of top level describe functions,
all top level tests and suites will execute.】
describe.skip([name][, options][, fn])#>
跳过测试套件的简写方式,与 describe([name], { skip: true }[, fn]) 相同。
【Shorthand for skipping a suite, same as describe([name], { skip: true }[, fn]).】
describe.todo([name][, options][, fn])#>
用于将测试套件标记为 TODO 的简写,与 describe([name], { todo: true }[, fn]) 相同。
【Shorthand for marking a suite as TODO, same as
describe([name], { todo: true }[, fn]).】
it([name][, options][, fn])#>
name<string> 测试的名称,在报告测试结果时显示。默认值:fn的name属性,或如果fn没有名称,则为'<anonymous>'。options<Object> 套件的配置选项。支持与test([名称][, options][, fn])相同的选项。fn<Function> | <AsyncFunction> 被测试的函数。如果测试使用回调函数,则回调函数作为参数传递。默认值: 一个无操作函数。- 返回:
undefined。
it() 函数是从 node:test 模块中导入的值。每次调用此函数都会在 TAP 输出中创建一个测试点。
【The it() function is the value imported from the node:test module.
Each invocation of this function results in the creation of a test point in the
TAP output.】
it.skip([name][, options][, fn])#>
跳过测试的简写,与 it([name], { skip: true }[, fn]) 相同。
【Shorthand for skipping a test,
same as it([name], { skip: true }[, fn]).】
it.todo([name][, options][, fn])#>
用于将测试标记为 TODO 的简写,和 it([name], { todo: true }[, fn]) 相同。
【Shorthand for marking a test as TODO,
same as it([name], { todo: true }[, fn]).】
before([, fn][, options])#>
fn<Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值: 一个空操作函数。options<Object> 钩子的配置选项。支持以下属性:signal<AbortSignal> 允许中止正在进行的钩子。timeout<number> 钩子将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值:Infinity。
此函数用于在运行套件之前创建一个钩子运行。
【This function is used to create a hook running before running a suite.】
describe('tests', async () => {
before(() => console.log('about to run some test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
after([, fn][, options])#>
fn<Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值: 一个空操作函数。options<Object> 钩子的配置选项。支持以下属性:signal<AbortSignal> 允许中止正在进行的钩子。timeout<number> 钩子将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值:Infinity。
该函数用于创建一个在运行套件后运行的钩子。
【This function is used to create a hook running after running a suite.】
describe('tests', async () => {
after(() => console.log('finished running tests'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
beforeEach([, fn][, options])#>
fn<Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值: 一个空操作函数。options<Object> 钩子的配置选项。支持以下属性:signal<AbortSignal> 允许中止正在进行的钩子。timeout<number> 钩子将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值:Infinity。
此函数用于在当前测试套件的每个子测试运行之前创建一个钩子。
【This function is used to create a hook running before each subtest of the current suite.】
describe('tests', async () => {
beforeEach(() => t.diagnostic('about to run a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
afterEach([, fn][, options])#>
fn<Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值: 一个空操作函数。options<Object> 钩子的配置选项。支持以下属性:signal<AbortSignal> 允许中止正在进行的钩子。timeout<number> 钩子将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值:Infinity。
此函数用于创建一个钩子,在当前测试的每个子测试之后运行。
【This function is used to create a hook running after each subtest of the current test.】
describe('tests', async () => {
afterEach(() => t.diagnostic('about to run a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
类:TapStream#>
【Class: TapStream】
成功调用 run() 方法将返回一个新的 <TapStream> 对象,流式输出 轻拍。
TapStream 将按测试定义的顺序触发事件
【A successful call to run() method will return a new <TapStream>
object, streaming a TAP output
TapStream will emit events, in the order of the tests definition】
事件:'test:diagnostic'#>
【Event: 'test:diagnostic'】
message<string> 诊断信息。
当调用 context.diagnostic 时触发。
【Emitted when context.diagnostic is called.】
事件:'test:fail'#>
【Event: 'test:fail'】
data<Object>duration<number> 测试持续时间。error<Error> 故障外壳测试失败。name<string> 测试名称。testNumber<number> 测试的序号。todo<string> | <undefined> 如果调用了context.todo,则存在skip<string> | <undefined> 仅在调用context.skip时出现
测试失败时触发。
【Emitted when a test fails.】
事件:'test:pass'#>
【Event: 'test:pass'】
data<Object>duration<number> 测试持续时间。name<string> 测试名称。testNumber<number> 测试的序号。todo<string> | <undefined> 如果调用了context.todo,则存在skip<string> | <undefined> 仅在调用context.skip时出现
测试通过时触发。
【Emitted when a test passes.】
类:TestContext#>
【Class: TestContext】
每个测试函数都会传入一个 TestContext 实例,以便与测试运行器进行交互。然而,TestContext 构造函数并未作为 API 的一部分公开。
【An instance of TestContext is passed to each test function in order to
interact with the test runner. However, the TestContext constructor is not
exposed as part of the API.】
context.beforeEach([, fn][, options])#>
fn<Function> | <AsyncFunction> 钩子函数。该函数的第一个参数是一个TestContext对象。如果钩子使用回调函数,则回调函数作为第二个参数传入。默认值: 一个空操作函数。options<Object> 钩子的配置选项。支持以下属性:signal<AbortSignal> 允许中止正在进行的钩子。timeout<number> 钩子将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值:Infinity。
此函数用于在当前测试的每个子测试之前创建一个钩子。
【This function is used to create a hook running before each subtest of the current test.】
test('top level test', async (t) => {
t.beforeEach((t) => t.diagnostic(`about to run ${t.name}`));
await t.test(
'This is a subtest',
(t) => {
assert.ok('some relevant assertion here');
}
);
});
context.afterEach([, fn][, options])#>
fn<Function> | <AsyncFunction> 钩子函数。该函数的第一个参数是一个TestContext对象。如果钩子使用回调函数,则回调函数作为第二个参数传入。默认值: 一个空操作函数。options<Object> 钩子的配置选项。支持以下属性:signal<AbortSignal> 允许中止正在进行的钩子。timeout<number> 钩子将在指定毫秒数后失败。如果未指定,子测试将继承父测试的此值。默认值:Infinity。
此函数用于创建一个钩子,在当前测试的每个子测试之后运行。
【This function is used to create a hook running after each subtest of the current test.】
test('top level test', async (t) => {
t.afterEach((t) => t.diagnostic(`finished running ${t.name}`));
await t.test(
'This is a subtest',
(t) => {
assert.ok('some relevant assertion here');
}
);
});
context.diagnostic(message)#>
message<string> 将作为 TAP 诊断显示的消息。
此函数用于将 TAP 诊断信息写入输出。任何诊断信息都会包含在测试结果的末尾。此函数不返回值。
【This function is used to write TAP diagnostics to the output. Any diagnostic information is included at the end of the test's results. This function does not return a value.】
test('top level test', (t) => {
t.diagnostic('A diagnostic message');
});
context.name#>
测试名称。
【The name of the test.】
context.runOnly(shouldRunOnlyTests)#>
shouldRunOnlyTests<boolean> 是否只运行only测试。
如果 shouldRunOnlyTests 为真,测试上下文将只运行设置了 only 选项的测试。否则,将运行所有测试。如果 Node.js 不是使用 --test-only 命令行选项启动的,则该函数无任何操作。
【If shouldRunOnlyTests is truthy, the test context will only run tests that
have the only option set. Otherwise, all tests are run. If Node.js was not
started with the --test-only command-line option, this function is a
no-op.】
test('top level test', (t) => {
// The test context can be set to run subtests with the 'only' option.
t.runOnly(true);
return Promise.all([
t.test('this subtest is now skipped'),
t.test('this subtest is run', { only: true }),
]);
});
context.signal#>
- <AbortSignal> 可在测试已被中止时用于中止测试子任务。
test('top level test', async (t) => {
await fetch('some/uri', { signal: t.signal });
});
context.skip([message])#>
message<string> 可选的跳过消息,将显示在 TAP 输出中。
此函数会导致测试的输出将测试标记为已跳过。如果提供了 message,它会包含在 TAP 输出中。调用 skip() 不会终止测试函数的执行。此函数不返回值。
【This function causes the test's output to indicate the test as skipped. If
message is provided, it is included in the TAP output. Calling skip() does
not terminate execution of the test function. This function does not return a
value.】
test('top level test', (t) => {
// Make sure to return here as well if the test contains additional logic.
t.skip('this is skipped');
});
context.todo([message])#>
message<string> 可选TODO消息,将显示在 TAP 输出中。
此函数会向测试的输出中添加一个 TODO 指令。如果提供了 message,它将包含在 TAP 输出中。调用 todo() 不会终止测试函数的执行。此函数不返回任何值。
【This function adds a TODO directive to the test's output. If message is
provided, it is included in the TAP output. Calling todo() does not terminate
execution of the test function. This function does not return a value.】
test('top level test', (t) => {
// This test is marked as `TODO`
t.todo('this is a todo');
});
context.test([name][, options][, fn])#>
name<string> 子测试的名称,在报告测试结果时显示。默认值:fn的name属性,或如果fn没有名称,则为'<anonymous>'。options<Object> 子测试的配置选项。支持以下属性:concurrency<number> 可以同时运行的测试数量。 如果未指定,子测试将继承其父测试的此值。 默认值:1。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() 函数相同。
【This function is used to create subtests under the current test. This function
behaves in the same fashion as the top level test() function.】
test('top level test', async (t) => {
await t.test(
'This is a subtest',
{ only: false, skip: false, concurrency: 1, todo: false },
(t) => {
assert.ok('some relevant assertion here');
}
);
});
类:SuiteContext#>
【Class: SuiteContext】
每个测试套件函数都会传入一个 SuiteContext 实例,以便与测试运行器进行交互。然而,SuiteContext 构造函数并未作为 API 的一部分公开。
【An instance of SuiteContext is passed to each suite function in order to
interact with the test runner. However, the SuiteContext constructor is not
exposed as part of the API.】
context.name#>
套件名称。
【The name of the suite.】
context.signal#>
- <AbortSignal> 可在测试已被中止时用于中止测试子任务。