node:test
Node.js test module, resolvable via both ESM import and CommonJS require
(as node:test). It is implemented as a guest-JavaScript test runner layered
over Elide's node:assert: it builds a test tree, executes
it with hooks and subtests, and reports results in nested TAP.
javascript
import test, { describe, it } from "node:test";
test("addition", (t) => {
t.assert.strictEqual(1 + 1, 2);
});
describe("math", () => {
it("multiplies", (t) => {
t.assert.strictEqual(2 * 3, 6);
});
});Implemented surface
Defining tests
| Export | Description |
|---|---|
test(name?, options?, fn) / it(...) | Define a test. it is an alias of test. |
describe(name?, options?, fn) / suite(...) | Group tests into a suite. suite is an alias of describe. |
.skip / .todo / .only | Modifiers on test / it / describe (e.g. test.skip(...)); —test-only filtering is honoured. |
Hooks
before, after, beforeEach, and afterEach register lifecycle hooks at the
top level or inside a describe / suite, and are also available per-test
through the test context.
Test context (t)
The function passed to a test receives a context object t:
| Member | Description |
|---|---|
t.assert.* | The node:assert surface, bound to the running test. |
t.test(...) | Define a nested subtest. |
t.before / t.after / t.beforeEach / t.afterEach | Per-test hooks. |
t.diagnostic(msg) | Emit a TAP diagnostic line. |
t.plan(count) | Declare the expected number of assertions. |
t.skip([msg]) / t.todo([msg]) | Mark the running test skipped / todo. |
t.mock | The test-scoped mock tracker (see below). |
t.signal | An AbortSignal tied to the test's timeout and lifetime. |
Mocking (mock)
The mock export (and t.mock) tracks and restores mocks:
| Member | Description |
|---|---|
mock.fn([original][, impl][, options]) | Create a mock function with call tracking. |
mock.method(obj, name[, impl][, options]) | Replace a method with a mock. |
mock.getter / mock.setter / mock.property | Mock accessors / data properties. |
mock.timers | Fake-timer controller (enable / tick / reset / …). |
mock.reset() / mock.restoreAll() | Reset call state / restore all mocks. |
test.assert exposes the same assertion surface at module scope.
Not implemented
The following are exported (or present on the context) but throw
ERR_METHOD_NOT_IMPLEMENTED when called:
run()— the programmatic runner entry point.t.assert.snapshot(...)/t.assert.fileSnapshot(...), and thetest.snapshot.*configuration setters (snapshot testing).mock.module(...)— module mocking.
See also
- Node.js upstream: