测试运行器


【Test runner】

源代码: 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.】

通过 test 模块创建的测试由单个函数组成,该函数可以通过三种方式之一进行处理:

【Tests created via the test module consist of a single function that is processed in one of three ways:】

  1. 如果同步函数抛出异常则被视为失败,否则被视为通过。
  2. 一个返回 Promise 的函数,如果 Promise 被拒绝则被视为失败,如果 Promise 成功则被视为通过。
  3. 一个接收回调函数的函数。如果回调的第一个参数接收到任何真值,则测试被视为失败。如果第一个参数传递的是假值,则测试被视为通过。如果测试函数既接收回调函数又返回一个 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 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.】