测试运行器
【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.】