Skip to content
jshacks.dev
Testing

Write a first test with node test and assert

Write and run a first test with the built-in node:test module and node:assert/strict, using node --test and no dependencies.

1 min read
Summarize in AI

Node.js 24 ships a test runner, so a first test needs no install. Import test from node:test and the strict assertions from node:assert/strict.

math.test.mjsJavaScript
import test from 'node:test';
import assert from 'node:assert/strict';

function add(a, b) {
  return a + b;
}

test('adds two numbers', () => {
  assert.equal(add(2, 3), 5);
});
Shell
node --test
Text
✔ adds two numbers (0.5ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 45.2

The timings will differ. node --test runs every file that matches the default patterns, such as *.test.mjs and files in a test directory, each in its own process. The assert/strict module makes equal use === and deepEqual use strict comparison, so assert.equal('5', 5) fails. See the test runner docs.

A failing assertion prints the expected and actual values with a diff, and the process exits with code 1, which is what CI looks at. Use .mjs or "type": "module" for the import syntax. The node:test module has been stable since Node.js 20.

Also inNode.js
Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read
Node.js

Write CSV rows with a stream

Write CSV rows to a file stream in Node.js 24, quote fields that hold commas or quotes per RFC 4180, and wait for drain so memory stays flat.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.