nodejs built in unit test library

March 12, 2024

© 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 22:22:26 +0000). nodejs built in unit test library. https://borui/blog/2024-03-12-en-nodejs-unit-test-std-lib.
@misc{
  borui2024,
  author = {borui},
  title = {nodejs built in unit test library},
  year = {2024},
  publisher = {borui's blog},
  journal = {borui's blog},
  url={https://borui/blog/2024-03-12-en-nodejs-unit-test-std-lib}
}

Intro

In the early days, if we want to write unit test for nodejs application, we have to use 3rd party libraries. To name a few, Mocha, Jest, the testing library.

The built in testing library is added in v16.17.0 and has became stable in node 20.0.0, before that only testing feature is the assertion testing. For example, in node 14.21.3, we can already use Assertion testing, but it is too basic. The library has been gradually adding features, such as mocking to capture the mock function calls, or describe, and reporters.

To see what apis are avaliable in a particular verion, go to Nodejs Offical Doc.

basic usage

Below is based on Node v16 doc:

node --test 

Node 16 only supports only one reporter format: the TAP format. But later more format was introduced.

For Node 20, the defeult format is spec, which is the human readable format.

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