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

ExportDescription
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 / .onlyModifiers 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:
MemberDescription
t.assert.*The node:assert surface, bound to the running test.
t.test(...)Define a nested subtest.
t.before / t.after / t.beforeEach / t.afterEachPer-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.mockThe test-scoped mock tracker (see below).
t.signalAn AbortSignal tied to the test's timeout and lifetime.

Mocking (mock)

The mock export (and t.mock) tracks and restores mocks:
MemberDescription
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.propertyMock accessors / data properties.
mock.timersFake-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 the test.snapshot.* configuration setters (snapshot testing).
  • mock.module(...) — module mocking.

See also

  • Node.js upstream: