Node.js 内置的单元测试库

March 12, 2024

简介

早年间,要给 Node.js 应用写单元测试,得依赖第三方库。 常见的有 Mocha、Jest 和 Testing Library。

Node.js 从 v16.17.0 开始提供内置测试库,到 v20.0.0 进入稳定阶段。再早一些,内置的测试功能只有断言。 例如,在 Node 14.21.3 里已经可以使用断言做测试,但功能比较基础。 后来测试库逐步加入了其他功能,包括用 mock 记录函数调用、用 describe 组织测试,以及选择不同的报告格式。

想知道某个版本支持哪些 API,可以查阅对应版本的 Node.js 官方文档。

基本用法

下面的示例来自 Node 16 的文档。

node --test 

Node 16 的测试报告只支持 TAP 格式。后续版本增加了更多格式。

在 Node 20 中,默认的 spec 格式方便人直接阅读。

const test = require('node:test');

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'));
  });
});

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-03-12). Node.js 内置的单元测试库. https://caiborui.com/blog/2024-03-12-en-nodejs-unit-test-std-lib-zhtrans

@misc{borui2024-77005d0e,
  author = {borui},
  title = {{Node.js 内置的单元测试库}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-03-12-en-nodejs-unit-test-std-lib-zhtrans}
}