Loading lesson path
Concept visual
Start at both ends
Introduction to Node.js Test Runner The built-in node:test module provides a lightweight, no-dependency framework for writing and running JavaScript tests directly in Node.js. Introduced as a stable API in Node.js 20, it's designed to be a fast, modern alternative to external testing frameworks.
The Node.js Test Runner is stable as of Node.js v20. Some advanced features may be experimental in earlier versions.
Works out of the box with no setup
Integration with Node.js coverage tools
Let's create and run a basic test using the Node.js Test Runner. You'll need Node.js 16.17.0 or later installed.
Formula
1. Create a test file (test/example.test.js)
// Load the test module const test = require('node:test');
// Use strict assertion mode for better error messages const assert = require('node:assert/strict');// Simple synchronous test test('basic arithmetic', (t) => {
// Assert that 1 + 1 equals 2 assert.equal(1 + 1, 2, '1 + 1 should equal 2');Formula
// Deep equality check for objects/arrays assert.deepEqual({ a: 1, b: { c: 2 } },
{ a: 1, b: { c: 2 } }
);
});
// Asynchronous test with async/await test('async test', async (t) => {
const result = await Promise.resolve('async result');
assert.strictEqual(result, 'async result');
});Formula
# Run a specific test file node -- test test/example.test.js# Run with coverage reporting
Formula
NODE_V8_COVERAGE = coverage node -- testFor larger projects, organize your tests in a structured way: project/ âââ src/ â âââ math.js â âââ utils.js âââ test/ âââ unit/ â âââ math.test.js â âââ utils.test.js âââ integration/ âââ api.test.js
Use hooks to set up and clean up test environments:
const { test, describe, before, after, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
describe('Test Suite with Hooks', (t) => {
let testData = [];
// Runs once before all tests before(() => {
console.log('Running before all tests');
testData = [1, 2, 3];
});
// Runs before each test beforeEach((t) => {
console.log('Running before each test');
});
test('array length', () => {
assert.strictEqual(testData.length, 3);
});
// Runs after each test afterEach(() => {
console.log('Running after each test');
});
// Runs once after all tests after(() => {
console.log('Running after all tests');
testData = [];
});
});// simple-test.js const test = require('node:test');
const assert = require('node:assert/strict');
test('basic test', () => {
assert.equal(1 + 1, 2);
});