Built-in Node.js Test Runner
Beginner10 minTrending
Use the built-in node --test runner for unit and integration testing without installing external test frameworks.
Prerequisites
- -Node.js 20 or later
Steps
1
Create a test file
Write a test file using the built-in node:test module with describe/it syntax.
$ cat <<'EOF' > math.test.js
const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { add, multiply } = require('./math.js');
describe('Math functions', () => {
it('should add two numbers', () => {
assert.strictEqual(add(2, 3), 5);
assert.strictEqual(add(-1, 1), 0);
});
it('should multiply two numbers', () => {
assert.strictEqual(multiply(3, 4), 12);
assert.strictEqual(multiply(0, 5), 0);
});
});
EOF
2
Run tests with the built-in runner
Execute all test files matching the default pattern using node --test.
$ node --test
By default, node --test finds files matching **/*.test.{js,mjs,cjs} and **/*-test.{js,mjs,cjs} patterns.
3
Run specific test files or use glob patterns
Target specific test files or directories instead of running the full suite.
$ node --test 'tests/**/*.test.js'
4
Use mocking capabilities
Use the built-in mock module to create spies, stubs, and mock functions.
$ cat <<'EOF' > api.test.js
const { describe, it, mock } = require('node:test');
const assert = require('node:assert/strict');
describe('API client', () => {
it('should call fetch with correct URL', async () => {
const mockFetch = mock.fn(async () => ({
json: async () => ({ data: 'test' })
}));
// Replace global fetch
mock.method(globalThis, 'fetch', mockFetch);
const { fetchData } = require('./api.js');
const result = await fetchData('/users');
assert.strictEqual(mockFetch.mock.calls.length, 1);
assert.ok(mockFetch.mock.calls[0].arguments[0].includes('/users'));
});
});
EOF
5
Generate test coverage reports
Run tests with coverage enabled to see which lines of code are tested.
$ node --test --experimental-test-coverage
Coverage reports show per-file line, branch, and function coverage percentages directly in the terminal.
Full Script
FAQ
Discussion
Loading comments...