Node.js Built-in Test Runner Unit Testing Guide

This article provides a practical guide on how to use the native, built-in test runner in Node.js to write and execute unit tests without relying on third-party frameworks like Jest or Mocha. You will learn how to structure your test files, write assertion statements using the built-in assert module, and run your test suite directly from the command line.

Introduction to node:test

Node.js (version 18 and later) includes a stable, built-in test runner. This module eliminates the need to install external testing libraries, reducing project dependencies and setup time. The core modules used for testing are node:test for structuring the tests and node:assert for verifying code outcomes.

Creating a Function to Test

First, create a simple JavaScript file containing the logic you want to test. Create a file named math.js with the following code:

// math.js
function add(a, b) {
  return a + b;
}

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}

module.exports = { add, divide };

Writing the Unit Tests

Next, create a test file. Node.js looks for files with extensions like .test.js or .spec.js. Create a file named math.test.js and import the necessary modules:

// math.test.js
const { describe, it } = require('node:test');
const assert = require('node:assert');
const { add, divide } = require('./math');

describe('Math Module Tests', () => {
  
  it('should correctly add two numbers', () => {
    const result = add(2, 3);
    assert.strictEqual(result, 5);
  });

  it('should correctly divide two numbers', () => {
    const result = divide(6, 2);
    assert.strictEqual(result, 3);
  });

  it('should throw an error when dividing by zero', () => {
    assert.throws(() => {
      divide(5, 0);
    }, /^Error: Cannot divide by zero$/);
  });
  
});

Running the Tests

To execute your tests, use the --test flag in your terminal. Node.js will automatically search for and execute files matching common test patterns:

node --test

To run a specific test file, pass the file path to the command:

node --test math.test.js

The terminal output will display a report indicating whether the tests passed or failed, along with the execution duration.

Common Assertion Methods

The node:assert module provides several functions to validate your code: