Unit tests
Verify synchronous functions and assertions without installing a test framework.
Node.js · Module
node:test is Node.js’s built-in test module. Define synchronous, Promise-based, or callback-based tests and run them with the Node.js test runner.
Import the built-in test function with the node: scheme, then provide a named test and a function. Synchronous tests pass when the function returns normally and fail when it throws; asynchronous tests may return a Promise, while callback-based tests report through their callback.
import test from 'node:test';
test(name[, options], fn)| Name | Type | Description |
|---|---|---|
test(name[, options], fn) | function | The test name and test function; the function may be synchronous, return a Promise, or use a callback. |
A test declaration; execution results are reported by the Node.js test runner in TAP format.
--test command-line option.test instead of node:test is unsupported; use the built-in module's node: prefix.import test from 'node:test';
import assert from 'node:assert/strict';
test('addition works', () => {
assert.equal(2 + 3, 5);
});Save as addition.test.js and run it with node --test addition.test.js.
Verify synchronous functions and assertions without installing a test framework.
Create nested test hierarchies for related cases.
Run tests from scripts or CI using Node's built-in runner.
Replace selected dependencies or collaborators during tests.
node:test used for?node:test is Node.js's built-in test module. Tests can be synchronous, Promise-based, or callback-based, and the runner can be started with node --test.
Follow-up: How would you organize nested cases? Use the test context's test() method to create hierarchical subtests.
A synchronous test fails if its function throws. A Promise-based test fails when its Promise rejects and passes when it fulfills.
Follow-up: What callback rule matters? A truthy first callback argument fails the test, while a falsy argument passes it.
The module is imported with node:test, and tests are commonly executed through the --test command-line flag. The runner emits test results in TAP format.
Follow-up: How can execution be narrowed? Use the --test-name-pattern option to select tests whose names match a JavaScript regular expression.
node:test/reportersTestContextdescribeitmock