测试运行器
¥Test runner
¥Stability: 2 - Stable
源代码: lib/test.js
node:test
模块有助于创建 JavaScript 测试。要访问它:
¥The node:test
module facilitates the creation of JavaScript tests.
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:
-
同步的函数,如果抛出异常则认为失败,否则认为通过。
¥A synchronous function that is considered failing if it throws an exception, and is considered passing otherwise.
-
返回
Promise
的函数,如果Promise
拒绝,则视为失败;如果Promise
满足,则视为通过。¥A function that returns a
Promise
that is considered failing if thePromise
rejects, and is considered passing if thePromise
fulfills. -
接收回调函数的函数。如果回调接收到任何真值作为其第一个参数,则认为测试失败。如果非真值作为第一个参数传给回调,则认为测试通过。如果测试函数接收到回调函数并且还返回
Promise
,则测试将失败。¥A function that receives a callback function. If the callback receives any truthy value as its first argument, the test is considered failing. If a falsy value is passed as the first argument to the callback, the test is considered passing. If the test function receives a callback function and also returns a
Promise
, the test will fail.
以下示例说明了如何使用 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 settled and 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'));
});
});
如果任何测试失败,则进程退出代码设置为 1
。
¥If any tests fail, the process exit code is set to 1
.