test
The node:test module facilitates the creation of JavaScript tests. To access it:
import test from 'node:test';
This module is only available under the node: scheme. The following will not work:
import test from 'node:test';
Tests created via the test module consist of a single function that is processed in one of three ways:
- A synchronous function that is considered failing if it throws an exception, and is considered passing otherwise.
- A function that returns a
Promisethat is considered failing if thePromiserejects, and is considered passing if thePromisefulfills. - A function that receives a callback function. If the callback receives any truthy value as its first argument, the test is considered failing. If a falsy value is passed as the first argument to the callback, the test is considered passing. If the test function receives a callback function and also returns a
Promise, the test will fail.
The following example illustrates how tests are written using the test module.
test('synchronous passing test', (t) => {
// This test passes because it does not throw an exception.
assert.strictEqual(1, 1);
});
test('synchronous failing test', (t) => {
// This test fails because it throws an exception.
assert.strictEqual(1, 2);
});
test('asynchronous passing test', async (t) => {
// This test passes because the Promise returned by the async
// function is settled and not rejected.
assert.strictEqual(1, 1);
});
test('asynchronous failing test', async (t) => {
// This test fails because the Promise returned by the async
// function is rejected.
assert.strictEqual(1, 2);
});
test('failing test using Promises', (t) => {
// Promises can be used directly as well.
return new Promise((resolve, reject) => {
setImmediate(() => {
reject(new Error('this will cause the test to fail'));
});
});
});
test('callback passing test', (t, done) => {
// done() is the callback function. When the setImmediate() runs, it invokes
// done() with no arguments.
setImmediate(done);
});
test('callback failing test', (t, done) => {
// When the setImmediate() runs, done() is invoked with an Error object and
// the test fails.
setImmediate(() => {
done(new Error('callback failure'));
});
});
If any tests fail, the process exit code is set to 1.
Usage in Deno
import * as mod from "node:test";
class MockFunctionContext
Usage in Deno
import { MockFunctionContext } from "node:test";
The MockFunctionContext class is used to inspect or manipulate the behavior of mocks created via the MockTracker APIs.
Type Parameters
F extends Function Properties
calls: Array<MockFunctionCall<F>> A getter that returns a copy of the internal array used to track calls to the mock. Each entry in the array is an object with the following properties.
Methods
callCount(): number This function returns the number of times that this mock has been invoked. This function is more efficient than checking ctx.calls.length because ctx.calls is a getter that creates a copy of the internal call tracking array.
mockImplementation(implementation: F): void This function is used to change the behavior of an existing mock.
The following example creates a mock function using t.mock.fn(), calls the mock function, and then changes the mock implementation to a different function.
test('changes a mock behavior', (t) => {
let cnt = 0;
function addOne() {
cnt++;
return cnt;
}
function addTwo() {
cnt += 2;
return cnt;
}
const fn = t.mock.fn(addOne);
assert.strictEqual(fn(), 1);
fn.mock.mockImplementation(addTwo);
assert.strictEqual(fn(), 3);
assert.strictEqual(fn(), 5);
});
mockImplementationOnce(
implementation: F,
onCall?: number,
): void This function is used to change the behavior of an existing mock for a single invocation. Once invocation onCall has occurred, the mock will revert to whatever behavior it would have used had mockImplementationOnce() not been called.
The following example creates a mock function using t.mock.fn(), calls the mock function, changes the mock implementation to a different function for the next invocation, and then resumes its previous behavior.
test('changes a mock behavior once', (t) => {
let cnt = 0;
function addOne() {
cnt++;
return cnt;
}
function addTwo() {
cnt += 2;
return cnt;
}
const fn = t.mock.fn(addOne);
assert.strictEqual(fn(), 1);
fn.mock.mockImplementationOnce(addTwo);
assert.strictEqual(fn(), 3);
assert.strictEqual(fn(), 4);
});
resetCalls(): void Resets the call history of the mock function.
restore(): void Resets the implementation of the mock function to its original behavior. The mock can still be used after calling this function.
class MockModuleContext
Usage in Deno
import { MockModuleContext } from "node:test";
Methods
restore(): void Resets the implementation of the mock module.
class MockTimers
Usage in Deno
import { MockTimers } from "node:test";
Mocking timers is a technique commonly used in software testing to simulate and control the behavior of timers, such as setInterval and setTimeout, without actually waiting for the specified time intervals.
The MockTimers API also allows for mocking of the Date constructor and setImmediate/clearImmediate functions.
The MockTracker provides a top-level timers export which is a MockTimers instance.
Methods
[Symbol.dispose](): void Calls MockTimers.reset().
enable(options?: MockTimersOptions): void Enables timer mocking for the specified timers.
Note: When you enable mocking for a specific timer, its associated clear function will also be implicitly mocked.
Note: Mocking Date will affect the behavior of the mocked timers as they use the same internal clock.
Example usage without setting initial time:
import { mock } from 'node:test';
mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 });
The above example enables mocking for the Date constructor, setInterval timer and implicitly mocks the clearInterval function. Only the Date constructor from globalThis, setInterval and clearInterval functions from node:timers, node:timers/promises, and globalThis will be mocked.
Example usage with initial time set
import { mock } from 'node:test';
mock.timers.enable({ apis: ['Date'], now: 1000 });
Example usage with initial Date object as time set
import { mock } from 'node:test';
mock.timers.enable({ apis: ['Date'], now: new Date() });
Alternatively, if you call mock.timers.enable() without any parameters:
All timers ('setInterval', 'clearInterval', 'Date', 'setImmediate', 'clearImmediate', 'setTimeout', and 'clearTimeout') will be mocked.
The setInterval, clearInterval, setTimeout, and clearTimeout functions from node:timers, node:timers/promises, and globalThis will be mocked. The Date constructor from globalThis will be mocked.
If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is January 1st, 1970, 00:00:00 UTC. You can set an initial date by passing a now property to the .enable() method. This value will be used as the initial date for the mocked Date object. It can either be a positive integer, or another Date object.
reset(): void This function restores the default behavior of all mocks that were previously created by this MockTimers instance and disassociates the mocks from the MockTracker instance.
Note: After each test completes, this function is called on the test context's MockTracker.
import { mock } from 'node:test';
mock.timers.reset();
runAll(): void Triggers all pending mocked timers immediately. If the Date object is also mocked, it will also advance the Date object to the furthest timer's time.
The example below triggers all pending timers immediately, causing them to execute without any delay.
import assert from 'node:assert';
import { test } from 'node:test';
test('runAll functions following the given order', (context) => {
context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
const results = [];
setTimeout(() => results.push(1), 9999);
// Notice that if both timers have the same timeout,
// the order of execution is guaranteed
setTimeout(() => results.push(3), 8888);
setTimeout(() => results.push(2), 8888);
assert.deepStrictEqual(results, []);
context.mock.timers.runAll();
assert.deepStrictEqual(results, [3, 2, 1]);
// The Date object is also advanced to the furthest timer's time
assert.strictEqual(Date.now(), 9999);
});
Note: The runAll() function is specifically designed for triggering timers in the context of timer mocking. It does not have any effect on real-time system clocks or actual timers outside of the mocking environment.
setTime(time: number): void You can use the .setTime() method to manually move the mocked date to another time. This method only accepts a positive integer. Note: This method will execute any mocked timers that are in the past from the new time. In the below example we are setting a new time for the mocked date.
import assert from 'node:assert';
import { test } from 'node:test';
test('sets the time of a date object', (context) => {
// Optionally choose what to mock
context.mock.timers.enable({ apis: ['Date'], now: 100 });
assert.strictEqual(Date.now(), 100);
// Advance in time will also advance the date
context.mock.timers.setTime(1000);
context.mock.timers.tick(200);
assert.strictEqual(Date.now(), 1200);
});
tick(milliseconds: number): void Advances time for all mocked timers.
Note: This diverges from how setTimeout in Node.js behaves and accepts only positive numbers. In Node.js, setTimeout with negative numbers is only supported for web compatibility reasons.
The following example mocks a setTimeout function and by using .tick advances in time triggering all pending timers.
import assert from 'node:assert';
import { test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
context.mock.timers.enable({ apis: ['setTimeout'] });
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
});
Alternativelly, the .tick function can be called many times
import assert from 'node:assert';
import { test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
context.mock.timers.enable({ apis: ['setTimeout'] });
const nineSecs = 9000;
setTimeout(fn, nineSecs);
const twoSeconds = 3000;
context.mock.timers.tick(twoSeconds);
context.mock.timers.tick(twoSeconds);
context.mock.timers.tick(twoSeconds);
assert.strictEqual(fn.mock.callCount(), 1);
});
Advancing time using .tick will also advance the time for any Date object created after the mock was enabled (if Date was also set to be mocked).
import assert from 'node:assert';
import { test } from 'node:test';
test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
const fn = context.mock.fn();
context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
setTimeout(fn, 9999);
assert.strictEqual(fn.mock.callCount(), 0);
assert.strictEqual(Date.now(), 0);
// Advance in time
context.mock.timers.tick(9999);
assert.strictEqual(fn.mock.callCount(), 1);
assert.strictEqual(Date.now(), 9999);
});
class MockTracker
Usage in Deno
import { MockTracker } from "node:test";
The MockTracker class is used to manage mocking functionality. The test runner module provides a top level mock export which is a MockTracker instance. Each test also provides its own MockTracker instance via the test context's mock property.
Properties
Methods
fn<F extends Function = NoOpFunction>(
original?: F,
options?: MockFunctionOptions,
): Mock<F> This function is used to create a mock function.
The following example creates a mock function that increments a counter by one on each invocation. The times option is used to modify the mock behavior such that the first two invocations add two to the counter instead of one.
test('mocks a counting function', (t) => {
let cnt = 0;
function addOne() {
cnt++;
return cnt;
}
function addTwo() {
cnt += 2;
return cnt;
}
const fn = t.mock.fn(addOne, addTwo, { times: 2 });
assert.strictEqual(fn(), 2);
assert.strictEqual(fn(), 4);
assert.strictEqual(fn(), 5);
assert.strictEqual(fn(), 6);
});
fn<
F extends Function = NoOpFunction,
Implementation extends Function = F,
>(): Mock<F | Implementation> getter<
MockedObject extends object,
MethodName extends keyof MockedObject,
>(): Mock<() => MockedObject[MethodName]> This function is syntax sugar for MockTracker.method with options.getter set to true.
getter<
MockedObject extends object,
MethodName extends keyof MockedObject,
Implementation extends Function,
>(
object: MockedObject,
methodName: MethodName,
implementation?: Implementation,
options?: MockFunctionOptions,
): Mock<(() => MockedObject[MethodName]) | Implementation> method<
MockedObject extends object,
MethodName extends FunctionPropertyNames<MockedObject>,
>(): MockedObject[MethodName] extends Function ? Mock<MockedObject[MethodName]> : never This function is used to create a mock on an existing object method. The following example demonstrates how a mock is created on an existing object method.
test('spies on an object method', (t) => {
const number = {
value: 5,
subtract(a) {
return this.value - a;
},
};
t.mock.method(number, 'subtract');
assert.strictEqual(number.subtract.mock.calls.length, 0);
assert.strictEqual(number.subtract(3), 2);
assert.strictEqual(number.subtract.mock.calls.length, 1);
const call = number.subtract.mock.calls[0];
assert.deepStrictEqual(call.arguments, [3]);
assert.strictEqual(call.result, 2);
assert.strictEqual(call.error, undefined);
assert.strictEqual(call.target, undefined);
assert.strictEqual(call.this, number);
});
method<
MockedObject extends object,
MethodName extends FunctionPropertyNames<MockedObject>,
Implementation extends Function,
>(
object: MockedObject,
methodName: MethodName,
implementation: Implementation,
options?: MockFunctionOptions,
): MockedObject[MethodName] extends Function ? Mock<MockedObject[MethodName] | Implementation> : never method<MockedObject extends object>(
object: MockedObject,
methodName: keyof MockedObject,
implementation: Function,
options: MockMethodOptions,
): Mock<Function> module(
specifier: string,
options?: MockModuleOptions,
): MockModuleContext This function is used to mock the exports of ECMAScript modules, CommonJS modules, and Node.js builtin modules. Any references to the original module prior to mocking are not impacted.
Only available through the --experimental-test-module-mocks flag.
reset(): void This function restores the default behavior of all mocks that were previously created by this MockTracker and disassociates the mocks from the MockTracker instance. Once disassociated, the mocks can still be used, but the MockTracker instance can no longer be used to reset their behavior or otherwise interact with them.
After each test completes, this function is called on the test context's MockTracker. If the global MockTracker is used extensively, calling this function manually is recommended.
restoreAll(): void This function restores the default behavior of all mocks that were previously created by this MockTracker. Unlike mock.reset(), mock.restoreAll() does not disassociate the mocks from the MockTracker instance.
setter<
MockedObject extends object,
MethodName extends keyof MockedObject,
>(): Mock<(value: MockedObject[MethodName]) => void> This function is syntax sugar for MockTracker.method with options.setter set to true.
setter<
MockedObject extends object,
MethodName extends keyof MockedObject,
Implementation extends Function,
>(
object: MockedObject,
methodName: MethodName,
implementation?: Implementation,
options?: MockFunctionOptions,
): Mock<((value: MockedObject[MethodName]) => void) | Implementation> class SuiteContext
Usage in Deno
import { SuiteContext } from "node:test";
An instance of SuiteContext is passed to each suite function in order to interact with the test runner. However, the SuiteContext constructor is not exposed as part of the API.
Properties
filePath: string | undefined The absolute path of the test file that created the current suite. If a test file imports additional modules that generate suites, the imported suites will return the path of the root test file.
name: string The name of the suite.
signal: AbortSignal Can be used to abort test subtasks when the test has been aborted.
class TestContext
Usage in Deno
import { TestContext } from "node:test";
An instance of TestContext is passed to each test function in order to interact with the test runner. However, the TestContext constructor is not exposed as part of the API.
Properties
assert: TestContextAssert An object containing assertion methods bound to the test context. The top-level functions from the node:assert module are exposed here for the purpose of creating test plans.
Note: Some of the functions from node:assert contain type assertions. If these are called via the TestContext assert object, then the context parameter in the test's function signature must be explicitly typed (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler:
import { test, type TestContext } from 'node:test';
// The test function's context parameter must have a type annotation.
test('example', (t: TestContext) => {
t.assert.deepStrictEqual(actual, expected);
});
// Omitting the type annotation will result in a compilation error.
test('example', t => {
t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation.
});
filePath: string | undefined The absolute path of the test file that created the current test. If a test file imports additional modules that generate tests, the imported tests will return the path of the root test file.
fullName: string The name of the test and each of its ancestors, separated by >.
mock: MockTracker Each test provides its own MockTracker instance.
name: string The name of the test.
signal: AbortSignal test('top level test', async (t) => {
await fetch('some/uri', { signal: t.signal });
});
Methods
after(
fn?: TestContextHookFn,
options?: HookOptions,
): void This function is used to create a hook that runs after the current test finishes.
afterEach(
fn?: TestContextHookFn,
options?: HookOptions,
): void This function is used to create a hook running after each subtest of the current test.
before(
fn?: TestContextHookFn,
options?: HookOptions,
): void This function is used to create a hook running before subtest of the current test.
beforeEach(
fn?: TestContextHookFn,
options?: HookOptions,
): void This function is used to create a hook running before each subtest of the current test.
diagnostic(message: string): void This function is used to write diagnostics to the output. Any diagnostic information is included at the end of the test's results. This function does not return a value.
test('top level test', (t) => {
t.diagnostic('A diagnostic message');
});
plan(count: number): void Used to set the number of assertions and subtests that are expected to run within the test. If the number of assertions and subtests that run does not match the expected count, the test will fail.
To make sure assertions are tracked, the assert functions on context.assert must be used, instead of importing from the node:assert module.
test('top level test', (t) => {
t.plan(2);
t.assert.ok('some relevant assertion here');
t.test('subtest', () => {});
});
When working with asynchronous code, the plan function can be used to ensure that the correct number of assertions are run:
test('planning with streams', (t, done) => {
function* generate() {
yield 'a';
yield 'b';
yield 'c';
}
const expected = ['a', 'b', 'c'];
t.plan(expected.length);
const stream = Readable.from(generate());
stream.on('data', (chunk) => {
t.assert.strictEqual(chunk, expected.shift());
});
stream.on('end', () => {
done();
});
});
runOnly(shouldRunOnlyTests: boolean): void If shouldRunOnlyTests is truthy, the test context will only run tests that have the only option set. Otherwise, all tests are run. If Node.js was not started with the --test-only command-line option, this function is a no-op.
test('top level test', (t) => {
// The test context can be set to run subtests with the 'only' option.
t.runOnly(true);
return Promise.all([
t.test('this subtest is now skipped'),
t.test('this subtest is run', { only: true }),
]);
});
skip(message?: string): void This function causes the test's output to indicate the test as skipped. If message is provided, it is included in the output. Calling skip() does not terminate execution of the test function. This function does not return a value.
test('top level test', (t) => {
// Make sure to return here as well if the test contains additional logic.
t.skip('this is skipped');
});
todo(message?: string): void This function adds a TODO directive to the test's output. If message is provided, it is included in the output. Calling todo() does not terminate execution of the test function. This function does not return a value.
test('top level test', (t) => {
// This test is marked as `TODO`
t.todo('this is a todo');
});
waitFor<T>(
condition: () => T,
options?: TestContextWaitForOptions,
): Promise<Awaited<T>> This method polls a condition function until that function either returns successfully or the operation times out.
class TestsStream
Usage in Deno
import { TestsStream } from "node:test";
A successful call to run() will return a new TestsStream object, streaming a series of events representing the execution of the tests.
Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute.
Methods
addListener(
event: "test:coverage",
listener: (data: TestCoverage) => void,
): this addListener(
event: "test:complete",
listener: (data: TestComplete) => void,
): this addListener(
event: "test:dequeue",
listener: (data: TestDequeue) => void,
): this addListener(
event: "test:diagnostic",
listener: (data: DiagnosticData) => void,
): this addListener(
event: "test:enqueue",
listener: (data: TestEnqueue) => void,
): this addListener(
event: "test:fail",
listener: (data: TestFail) => void,
): this addListener(
event: "test:pass",
listener: (data: TestPass) => void,
): this addListener(
event: "test:plan",
listener: (data: TestPlan) => void,
): this addListener(
event: "test:start",
listener: (data: TestStart) => void,
): this addListener(
event: "test:stderr",
listener: (data: TestStderr) => void,
): this addListener(
event: "test:stdout",
listener: (data: TestStdout) => void,
): this addListener(
event: "test:summary",
listener: (data: TestSummary) => void,
): this addListener(
event: "test:watch:drained",
listener: () => void,
): this addListener(
event: string,
listener: (...args: any[]) => void,
): this emit(
event: "test:coverage",
data: TestCoverage,
): boolean emit(
event: "test:complete",
data: TestComplete,
): boolean emit(
event: "test:dequeue",
data: TestDequeue,
): boolean emit(
event: "test:diagnostic",
data: DiagnosticData,
): boolean emit(
event: "test:enqueue",
data: TestEnqueue,
): boolean emit(
event: "test:fail",
data: TestFail,
): boolean emit(
event: "test:pass",
data: TestPass,
): boolean emit(
event: "test:plan",
data: TestPlan,
): boolean emit(
event: "test:start",
data: TestStart,
): boolean emit(
event: "test:stderr",
data: TestStderr,
): boolean emit(
event: "test:stdout",
data: TestStdout,
): boolean emit(
event: "test:summary",
data: TestSummary,
): boolean emit(event: "test:watch:drained"): boolean emit(
event: string | symbol,
...args: any[],
): boolean on(
event: "test:coverage",
listener: (data: TestCoverage) => void,
): this on(
event: "test:complete",
listener: (data: TestComplete) => void,
): this on(
event: "test:dequeue",
listener: (data: TestDequeue) => void,
): this on(
event: "test:diagnostic",
listener: (data: DiagnosticData) => void,
): this on(
event: "test:enqueue",
listener: (data: TestEnqueue) => void,
): this on(
event: "test:fail",
listener: (data: TestFail) => void,
): this on(
event: "test:pass",
listener: (data: TestPass) => void,
): this on(
event: "test:plan",
listener: (data: TestPlan) => void,
): this on(
event: "test:start",
listener: (data: TestStart) => void,
): this on(
event: "test:stderr",
listener: (data: TestStderr) => void,
): this on(
event: "test:stdout",
listener: (data: TestStdout) => void,
): this on(
event: "test:summary",
listener: (data: TestSummary) => void,
): this on(
event: "test:watch:drained",
listener: () => void,
): this on(
event: string,
listener: (...args: any[]) => void,
): this once(
event: "test:coverage",
listener: (data: TestCoverage) => void,
): this once(
event: "test:complete",
listener: (data: TestComplete) => void,
): this once(
event: "test:dequeue",
listener: (data: TestDequeue) => void,
): this once(
event: "test:diagnostic",
listener: (data: DiagnosticData) => void,
): this once(
event: "test:enqueue",
listener: (data: TestEnqueue) => void,
): this once(
event: "test:fail",
listener: (data: TestFail) => void,
): this once(
event: "test:pass",
listener: (data: TestPass) => void,
): this once(
event: "test:plan",
listener: (data: TestPlan) => void,
): this once(
event: "test:start",
listener: (data: TestStart) => void,
): this once(
event: "test:stderr",
listener: (data: TestStderr) => void,
): this once(
event: "test:stdout",
listener: (data: TestStdout) => void,
): this once(
event: "test:summary",
listener: (data: TestSummary) => void,
): this once(
event: "test:watch:drained",
listener: () => void,
): this once(
event: string,
listener: (...args: any[]) => void,
): this prependListener(
event: "test:coverage",
listener: (data: TestCoverage) => void,
): this prependListener(
event: "test:complete",
listener: (data: TestComplete) => void,
): this prependListener(
event: "test:dequeue",
listener: (data: TestDequeue) => void,
): this prependListener(
event: "test:diagnostic",
listener: (data: DiagnosticData) => void,
): this prependListener(
event: "test:enqueue",
listener: (data: TestEnqueue) => void,
): this prependListener(
event: "test:fail",
listener: (data: TestFail) => void,
): this prependListener(
event: "test:pass",
listener: (data: TestPass) => void,
): this prependListener(
event: "test:plan",
listener: (data: TestPlan) => void,
): this prependListener(
event: "test:start",
listener: (data: TestStart) => void,
): this prependListener(
event: "test:stderr",
listener: (data: TestStderr) => void,
): this prependListener(
event: "test:stdout",
listener: (data: TestStdout) => void,
): this prependListener(
event: "test:summary",
listener: (data: TestSummary) => void,
): this prependListener(
event: "test:watch:drained",
listener: () => void,
): this prependListener(
event: string,
listener: (...args: any[]) => void,
): this prependOnceListener(
event: "test:coverage",
listener: (data: TestCoverage) => void,
): this prependOnceListener(
event: "test:complete",
listener: (data: TestComplete) => void,
): this prependOnceListener(
event: "test:dequeue",
listener: (data: TestDequeue) => void,
): this prependOnceListener(
event: "test:diagnostic",
listener: (data: DiagnosticData) => void,
): this prependOnceListener(
event: "test:enqueue",
listener: (data: TestEnqueue) => void,
): this prependOnceListener(
event: "test:fail",
listener: (data: TestFail) => void,
): this prependOnceListener(
event: "test:pass",
listener: (data: TestPass) => void,
): this prependOnceListener(
event: "test:plan",
listener: (data: TestPlan) => void,
): this prependOnceListener(
event: "test:start",
listener: (data: TestStart) => void,
): this prependOnceListener(
event: "test:stderr",
listener: (data: TestStderr) => void,
): this prependOnceListener(
event: "test:stdout",
listener: (data: TestStdout) => void,
): this prependOnceListener(
event: "test:summary",
listener: (data: TestSummary) => void,
): this prependOnceListener(
event: "test:watch:drained",
listener: () => void,
): this prependOnceListener(
event: string,
listener: (...args: any[]) => void,
): this function after
Usage in Deno
import { after } from "node:test";
after(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs after executing a suite.
describe('tests', async () => {
after(() => console.log('finished running tests'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function afterEach
Usage in Deno
import { afterEach } from "node:test";
afterEach(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs after each test in the current suite. The afterEach() hook is run even if the test fails.
describe('tests', async () => {
afterEach(() => console.log('finished running a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function assert.register
Usage in Deno
import { assert } from "node:test";
register(
name: string,
fn: (
this: TestContext,
...args: any[],
) => void,
): voidDefines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
Parameters
name: string fn: (
this: TestContext,
...args: any[],
) => void Return Type
void function before
Usage in Deno
import { before } from "node:test";
before(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs before executing a suite.
describe('tests', async () => {
before(() => console.log('about to run some test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function beforeEach
Usage in Deno
import { beforeEach } from "node:test";
beforeEach(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs before each test in the current suite.
describe('tests', async () => {
beforeEach(() => console.log('about to run a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function default
Usage in Deno
import mod from "node:test";
Overload 1
default(
name?: string,
fn?: TestFn,
): Promise<void>The test() function is the value imported from the test module. Each invocation of this function results in reporting the test to the TestsStream.
The TestContext object passed to the fn argument can be used to perform actions related to the current test. Examples include skipping the test, adding additional diagnostic information, or creating subtests.
test() returns a Promise that fulfills once the test completes. if test() is called within a suite, it fulfills immediately. The return value can usually be discarded for top level tests. However, the return value from subtests should be used to prevent the parent test from finishing first and cancelling the subtest as shown in the following example.
test('top level test', async (t) => {
// The setTimeout() in the following subtest would cause it to outlive its
// parent test if 'await' is removed on the next line. Once the parent test
// completes, it will cancel any outstanding subtests.
await t.test('longer running subtest', async (t) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
});
});
});
The timeout option can be used to fail the test if it takes longer than timeout milliseconds to complete. However, it is not a reliable mechanism for canceling tests because a running test might block the application thread and thus prevent the scheduled cancellation.
Parameters
name: string The name of the test, which is displayed when reporting test results. Defaults to the name property of fn, or '<anonymous>' if fn does not have a name.
fn: TestFn The function under test. The first argument to this function is a TestContext object. If the test uses callbacks, the callback function is passed as the second argument.
Return Type
Promise<void> Fulfilled with undefined once the test completes, or immediately if the test runs within a suite.
Overload 2
default(): Promise<void>Parameters
Return Type
Promise<void> Overload 3
default(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
namespace default
Functions
This function creates a hook that runs after executing a suite.
This function creates a hook that runs after each test in the current suite. The afterEach() hook is run even if the test fails.
This function creates a hook that runs before executing a suite.
This function creates a hook that runs before each test in the current suite.
Alias for suite.
Alias for test.
Shorthand for marking a test as only. This is the same as calling test with options.only set to true.
Note: shard is used to horizontally parallelize test running across machines or processes, ideal for large-scale executions across varied environments. It's incompatible with watch mode, tailored for rapid code iteration by automatically rerunning tests on file changes.
Shorthand for skipping a test. This is the same as calling test with options.skip set to true.
The suite() function is imported from the node:test module.
Shorthand for marking a test as TODO. This is the same as calling test with options.todo set to true.
Namespaces
An object whose methods are used to configure available assertions on the TestContext objects in the current process. The methods from node:assert and snapshot testing functions are available by default.
Variables
function default.after
Usage in Deno
import mod from "node:test";
after(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs after executing a suite.
describe('tests', async () => {
after(() => console.log('finished running tests'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function default.afterEach
Usage in Deno
import mod from "node:test";
afterEach(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs after each test in the current suite. The afterEach() hook is run even if the test fails.
describe('tests', async () => {
afterEach(() => console.log('finished running a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function default.assert.register
Usage in Deno
import mod from "node:test";
register(
name: string,
fn: (
this: TestContext,
...args: any[],
) => void,
): voidDefines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
Parameters
name: string fn: (
this: TestContext,
...args: any[],
) => void Return Type
void function default.before
Usage in Deno
import mod from "node:test";
before(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs before executing a suite.
describe('tests', async () => {
before(() => console.log('about to run some test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function default.beforeEach
Usage in Deno
import mod from "node:test";
beforeEach(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs before each test in the current suite.
describe('tests', async () => {
beforeEach(() => console.log('about to run a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function default.describe
Usage in Deno
import mod from "node:test";
Overload 1
describe(): Promise<void>Alias for suite.
The describe() function is imported from the node:test module.
Parameters
Return Type
Promise<void> Overload 2
describe(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
describe(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
namespace default.describe
Functions
Shorthand for marking a suite as only. This is the same as calling describe with options.only set to true.
Shorthand for skipping a suite. This is the same as calling describe with options.skip set to true.
Shorthand for marking a suite as TODO. This is the same as calling describe with options.todo set to true.
function default.describe.only
Usage in Deno
import mod from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a suite as only. This is the same as calling describe with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function default.describe.skip
Usage in Deno
import mod from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a suite. This is the same as calling describe with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function default.describe.todo
Usage in Deno
import mod from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a suite as TODO. This is the same as calling describe with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function default.it
Usage in Deno
import mod from "node:test";
Overload 1
it(): Promise<void>Alias for test.
The it() function is imported from the node:test module.
Parameters
Return Type
Promise<void> Overload 2
it(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
it(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
namespace default.it
Functions
Shorthand for marking a test as only. This is the same as calling it with options.only set to true.
Shorthand for skipping a test. This is the same as calling it with options.skip set to true.
Shorthand for marking a test as TODO. This is the same as calling it with options.todo set to true.
function default.it.only
Usage in Deno
import mod from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a test as only. This is the same as calling it with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function default.it.skip
Usage in Deno
import mod from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a test. This is the same as calling it with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function default.it.todo
Usage in Deno
import mod from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a test as TODO. This is the same as calling it with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function default.only
Usage in Deno
import mod from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a test as only. This is the same as calling test with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function default.run
Usage in Deno
import mod from "node:test";
run(options?: RunOptions): TestsStreamNote: shard is used to horizontally parallelize test running across machines or processes, ideal for large-scale executions across varied environments. It's incompatible with watch mode, tailored for rapid code iteration by automatically rerunning tests on file changes.
import { tap } from 'node:test/reporters';
import { run } from 'node:test';
import process from 'node:process';
import path from 'node:path';
run({ files: [path.resolve('./tests/test.js')] })
.compose(tap)
.pipe(process.stdout);
Parameters
options: RunOptions Configuration options for running tests.
Return Type
function default.skip
Usage in Deno
import mod from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a test. This is the same as calling test with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function default.snapshot.setDefaultSnapshotSerializers
Usage in Deno
import mod from "node:test";
setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): voidThis function is used to customize the default serialization mechanism used by the test runner.
By default, the test runner performs serialization by calling JSON.stringify(value, null, 2) on the provided value. JSON.stringify() does have limitations regarding circular structures and supported data types. If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers.
Serializers are called in order, with the output of the previous serializer passed as input to the next. The final result must be a string value.
Parameters
serializers: ReadonlyArray<(value: any) => any> An array of synchronous functions used as the default serializers for snapshot tests.
Return Type
void function default.snapshot.setResolveSnapshotPath
Usage in Deno
import mod from "node:test";
setResolveSnapshotPath(fn: (path: string | undefined) => string): voidThis function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. By default, the snapshot filename is the same as the entry point filename with .snapshot appended.
Parameters
fn: (path: string | undefined) => string A function used to compute the location of the snapshot file. The function receives the path of the test file as its only argument. If the test is not associated with a file (for example in the REPL), the input is undefined. fn() must return a string specifying the location of the snapshot file.
Return Type
void function default.suite
Usage in Deno
import mod from "node:test";
Overload 1
suite(): Promise<void>The suite() function is imported from the node:test module.
Parameters
name: string The name of the suite, which is displayed when reporting test results. Defaults to the name property of fn, or '<anonymous>' if fn does not have a name.
options: TestOptions Configuration options for the suite. This supports the same options as test.
fn: SuiteFn The suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
Return Type
Promise<void> Immediately fulfilled with undefined.
Overload 2
suite(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
suite(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
namespace default.suite
Functions
Shorthand for marking a suite as only. This is the same as calling suite with options.only set to true.
Shorthand for skipping a suite. This is the same as calling suite with options.skip set to true.
Shorthand for marking a suite as TODO. This is the same as calling suite with options.todo set to true.
function default.suite.only
Usage in Deno
import mod from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a suite as only. This is the same as calling suite with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function default.suite.skip
Usage in Deno
import mod from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a suite. This is the same as calling suite with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function default.suite.todo
Usage in Deno
import mod from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a suite as TODO. This is the same as calling suite with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function default.todo
Usage in Deno
import mod from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a test as TODO. This is the same as calling test with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function describe
Usage in Deno
import { describe } from "node:test";
Overload 1
describe(): Promise<void>Alias for suite.
The describe() function is imported from the node:test module.
Parameters
Return Type
Promise<void> Overload 2
describe(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
describe(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
namespace describe
Functions
Shorthand for marking a suite as only. This is the same as calling describe with options.only set to true.
Shorthand for skipping a suite. This is the same as calling describe with options.skip set to true.
Shorthand for marking a suite as TODO. This is the same as calling describe with options.todo set to true.
function describe.only
Usage in Deno
import { describe } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a suite as only. This is the same as calling describe with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function describe.skip
Usage in Deno
import { describe } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a suite. This is the same as calling describe with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function describe.todo
Usage in Deno
import { describe } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a suite as TODO. This is the same as calling describe with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function it
Usage in Deno
import { it } from "node:test";
Overload 1
it(): Promise<void>Alias for test.
The it() function is imported from the node:test module.
Parameters
Return Type
Promise<void> Overload 2
it(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
it(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
namespace it
Functions
function it.only
Usage in Deno
import { it } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a test as only. This is the same as calling it with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function it.skip
Usage in Deno
import { it } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a test. This is the same as calling it with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function it.todo
Usage in Deno
import { it } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a test as TODO. This is the same as calling it with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function only
Usage in Deno
import { only } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a test as only. This is the same as calling test with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function run
Usage in Deno
import { run } from "node:test";
run(options?: RunOptions): TestsStreamNote: shard is used to horizontally parallelize test running across machines or processes, ideal for large-scale executions across varied environments. It's incompatible with watch mode, tailored for rapid code iteration by automatically rerunning tests on file changes.
import { tap } from 'node:test/reporters';
import { run } from 'node:test';
import process from 'node:process';
import path from 'node:path';
run({ files: [path.resolve('./tests/test.js')] })
.compose(tap)
.pipe(process.stdout);
Parameters
options: RunOptions Configuration options for running tests.
Return Type
function skip
Usage in Deno
import { skip } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a test. This is the same as calling test with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function snapshot.setDefaultSnapshotSerializers
Usage in Deno
import { snapshot } from "node:test";
setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): voidThis function is used to customize the default serialization mechanism used by the test runner.
By default, the test runner performs serialization by calling JSON.stringify(value, null, 2) on the provided value. JSON.stringify() does have limitations regarding circular structures and supported data types. If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers.
Serializers are called in order, with the output of the previous serializer passed as input to the next. The final result must be a string value.
Parameters
serializers: ReadonlyArray<(value: any) => any> An array of synchronous functions used as the default serializers for snapshot tests.
Return Type
void function snapshot.setResolveSnapshotPath
Usage in Deno
import { snapshot } from "node:test";
setResolveSnapshotPath(fn: (path: string | undefined) => string): voidThis function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. By default, the snapshot filename is the same as the entry point filename with .snapshot appended.
Parameters
fn: (path: string | undefined) => string A function used to compute the location of the snapshot file. The function receives the path of the test file as its only argument. If the test is not associated with a file (for example in the REPL), the input is undefined. fn() must return a string specifying the location of the snapshot file.
Return Type
void function suite
Usage in Deno
import { suite } from "node:test";
Overload 1
suite(): Promise<void>The suite() function is imported from the node:test module.
Parameters
name: string The name of the suite, which is displayed when reporting test results. Defaults to the name property of fn, or '<anonymous>' if fn does not have a name.
options: TestOptions Configuration options for the suite. This supports the same options as test.
fn: SuiteFn The suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
Return Type
Promise<void> Immediately fulfilled with undefined.
Overload 2
suite(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
suite(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
namespace suite
Functions
Shorthand for marking a suite as only. This is the same as calling suite with options.only set to true.
Shorthand for skipping a suite. This is the same as calling suite with options.skip set to true.
Shorthand for marking a suite as TODO. This is the same as calling suite with options.todo set to true.
function suite.only
Usage in Deno
import { suite } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a suite as only. This is the same as calling suite with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function suite.skip
Usage in Deno
import { suite } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a suite. This is the same as calling suite with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function suite.todo
Usage in Deno
import { suite } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a suite as TODO. This is the same as calling suite with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function test
Usage in Deno
import { test } from "node:test";
Overload 1
test(
name?: string,
fn?: TestFn,
): Promise<void>The test() function is the value imported from the test module. Each invocation of this function results in reporting the test to the TestsStream.
The TestContext object passed to the fn argument can be used to perform actions related to the current test. Examples include skipping the test, adding additional diagnostic information, or creating subtests.
test() returns a Promise that fulfills once the test completes. if test() is called within a suite, it fulfills immediately. The return value can usually be discarded for top level tests. However, the return value from subtests should be used to prevent the parent test from finishing first and cancelling the subtest as shown in the following example.
test('top level test', async (t) => {
// The setTimeout() in the following subtest would cause it to outlive its
// parent test if 'await' is removed on the next line. Once the parent test
// completes, it will cancel any outstanding subtests.
await t.test('longer running subtest', async (t) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
});
});
});
The timeout option can be used to fail the test if it takes longer than timeout milliseconds to complete. However, it is not a reliable mechanism for canceling tests because a running test might block the application thread and thus prevent the scheduled cancellation.
Parameters
name: string The name of the test, which is displayed when reporting test results. Defaults to the name property of fn, or '<anonymous>' if fn does not have a name.
fn: TestFn The function under test. The first argument to this function is a TestContext object. If the test uses callbacks, the callback function is passed as the second argument.
Return Type
Promise<void> Fulfilled with undefined once the test completes, or immediately if the test runs within a suite.
Overload 2
test(): Promise<void>Parameters
Return Type
Promise<void> Overload 3
test(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
namespace test
Functions
This function creates a hook that runs after executing a suite.
This function creates a hook that runs after each test in the current suite. The afterEach() hook is run even if the test fails.
This function creates a hook that runs before executing a suite.
This function creates a hook that runs before each test in the current suite.
Alias for suite.
Note: shard is used to horizontally parallelize test running across machines or processes, ideal for large-scale executions across varied environments. It's incompatible with watch mode, tailored for rapid code iteration by automatically rerunning tests on file changes.
The suite() function is imported from the node:test module.
Namespaces
An object whose methods are used to configure available assertions on the TestContext objects in the current process. The methods from node:assert and snapshot testing functions are available by default.
Variables
function test.after
Usage in Deno
import { test } from "node:test";
after(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs after executing a suite.
describe('tests', async () => {
after(() => console.log('finished running tests'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function test.afterEach
Usage in Deno
import { test } from "node:test";
afterEach(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs after each test in the current suite. The afterEach() hook is run even if the test fails.
describe('tests', async () => {
afterEach(() => console.log('finished running a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function test.assert.register
Usage in Deno
import { test } from "node:test";
register(
name: string,
fn: (
this: TestContext,
...args: any[],
) => void,
): voidDefines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
Parameters
name: string fn: (
this: TestContext,
...args: any[],
) => void Return Type
void function test.before
Usage in Deno
import { test } from "node:test";
before(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs before executing a suite.
describe('tests', async () => {
before(() => console.log('about to run some test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function test.beforeEach
Usage in Deno
import { test } from "node:test";
beforeEach(
fn?: HookFn,
options?: HookOptions,
): voidThis function creates a hook that runs before each test in the current suite.
describe('tests', async () => {
beforeEach(() => console.log('about to run a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
});
Parameters
fn: HookFn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
options: HookOptions Configuration options for the hook.
Return Type
void function test.describe
Usage in Deno
import { test } from "node:test";
Overload 1
describe(): Promise<void>Alias for suite.
The describe() function is imported from the node:test module.
Parameters
Return Type
Promise<void> Overload 2
describe(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
describe(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
namespace test.describe
Functions
Shorthand for marking a suite as only. This is the same as calling describe with options.only set to true.
Shorthand for skipping a suite. This is the same as calling describe with options.skip set to true.
Shorthand for marking a suite as TODO. This is the same as calling describe with options.todo set to true.
function test.describe.only
Usage in Deno
import { test } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a suite as only. This is the same as calling describe with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function test.describe.skip
Usage in Deno
import { test } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a suite. This is the same as calling describe with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function test.describe.todo
Usage in Deno
import { test } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a suite as TODO. This is the same as calling describe with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function test.it
Usage in Deno
import { test } from "node:test";
Overload 1
it(): Promise<void>Alias for test.
The it() function is imported from the node:test module.
Parameters
Return Type
Promise<void> Overload 2
it(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
it(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
namespace test.it
Functions
Shorthand for marking a test as only. This is the same as calling it with options.only set to true.
Shorthand for skipping a test. This is the same as calling it with options.skip set to true.
Shorthand for marking a test as TODO. This is the same as calling it with options.todo set to true.
function test.it.only
Usage in Deno
import { test } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a test as only. This is the same as calling it with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function test.it.skip
Usage in Deno
import { test } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a test. This is the same as calling it with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function test.it.todo
Usage in Deno
import { test } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a test as TODO. This is the same as calling it with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function test.only
Usage in Deno
import { test } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a test as only. This is the same as calling test with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function test.run
Usage in Deno
import { test } from "node:test";
run(options?: RunOptions): TestsStreamNote: shard is used to horizontally parallelize test running across machines or processes, ideal for large-scale executions across varied environments. It's incompatible with watch mode, tailored for rapid code iteration by automatically rerunning tests on file changes.
import { tap } from 'node:test/reporters';
import { run } from 'node:test';
import process from 'node:process';
import path from 'node:path';
run({ files: [path.resolve('./tests/test.js')] })
.compose(tap)
.pipe(process.stdout);
Parameters
options: RunOptions Configuration options for running tests.
Return Type
function test.skip
Usage in Deno
import { test } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a test. This is the same as calling test with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function test.snapshot.setDefaultSnapshotSerializers
Usage in Deno
import { test } from "node:test";
setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): voidThis function is used to customize the default serialization mechanism used by the test runner.
By default, the test runner performs serialization by calling JSON.stringify(value, null, 2) on the provided value. JSON.stringify() does have limitations regarding circular structures and supported data types. If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers.
Serializers are called in order, with the output of the previous serializer passed as input to the next. The final result must be a string value.
Parameters
serializers: ReadonlyArray<(value: any) => any> An array of synchronous functions used as the default serializers for snapshot tests.
Return Type
void function test.snapshot.setResolveSnapshotPath
Usage in Deno
import { test } from "node:test";
setResolveSnapshotPath(fn: (path: string | undefined) => string): voidThis function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. By default, the snapshot filename is the same as the entry point filename with .snapshot appended.
Parameters
fn: (path: string | undefined) => string A function used to compute the location of the snapshot file. The function receives the path of the test file as its only argument. If the test is not associated with a file (for example in the REPL), the input is undefined. fn() must return a string specifying the location of the snapshot file.
Return Type
void function test.suite
Usage in Deno
import { test } from "node:test";
Overload 1
suite(): Promise<void>The suite() function is imported from the node:test module.
Parameters
name: string The name of the suite, which is displayed when reporting test results. Defaults to the name property of fn, or '<anonymous>' if fn does not have a name.
options: TestOptions Configuration options for the suite. This supports the same options as test.
fn: SuiteFn The suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
Return Type
Promise<void> Immediately fulfilled with undefined.
Overload 2
suite(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
suite(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
namespace test.suite
Functions
Shorthand for marking a suite as only. This is the same as calling suite with options.only set to true.
Shorthand for skipping a suite. This is the same as calling suite with options.skip set to true.
Shorthand for marking a suite as TODO. This is the same as calling suite with options.todo set to true.
function test.suite.only
Usage in Deno
import { test } from "node:test";
Overload 1
only(): Promise<void>Shorthand for marking a suite as only. This is the same as calling suite with options.only set to true.
Parameters
Return Type
Promise<void> Overload 2
only(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
only(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function test.suite.skip
Usage in Deno
import { test } from "node:test";
Overload 1
skip(): Promise<void>Shorthand for skipping a suite. This is the same as calling suite with options.skip set to true.
Parameters
Return Type
Promise<void> Overload 2
skip(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
skip(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function test.suite.todo
Usage in Deno
import { test } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a suite as TODO. This is the same as calling suite with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: SuiteFn,
): Promise<void>Parameters
name: string fn: SuiteFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: SuiteFn,
): Promise<void>Parameters
options: TestOptions fn: SuiteFn Return Type
Promise<void> Overload 4
function test.todo
Usage in Deno
import { test } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a test as TODO. This is the same as calling test with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
function todo
Usage in Deno
import { todo } from "node:test";
Overload 1
todo(): Promise<void>Shorthand for marking a test as TODO. This is the same as calling test with options.todo set to true.
Parameters
Return Type
Promise<void> Overload 2
todo(
name?: string,
fn?: TestFn,
): Promise<void>Parameters
name: string fn: TestFn Return Type
Promise<void> Overload 3
todo(
options?: TestOptions,
fn?: TestFn,
): Promise<void>Parameters
options: TestOptions fn: TestFn Return Type
Promise<void> Overload 4
interface AssertSnapshotOptions
Usage in Deno
import { type AssertSnapshotOptions } from "node:test";
Properties
serializers: ReadonlyArray<(value: any) => any> | undefined An array of synchronous functions used to serialize value into a string. value is passed as the only argument to the first serializer function. The return value of each serializer is passed as input to the next serializer. Once all serializers have run, the resulting value is coerced to a string.
If no serializers are provided, the test runner's default serializers are used.
interface HookOptions
Usage in Deno
import { type HookOptions } from "node:test";
interface MockFunctionCall
Usage in Deno
import { type MockFunctionCall } from "node:test";
Type Parameters
Properties
error: unknown | undefined If the mocked function threw then this property contains the thrown value.
result: ReturnType | undefined The value returned by the mocked function.
If the mocked function threw, it will be undefined.
stack: Error An Error object whose stack can be used to determine the callsite of the mocked function invocation.
If the mocked function is a constructor, this field contains the class being constructed. Otherwise this will be undefined.
this: unknown The mocked function's this value.
interface MockFunctionOptions
Usage in Deno
import { type MockFunctionOptions } from "node:test";
Properties
times: number | undefined The number of times that the mock will use the behavior of implementation. Once the mock function has been called times times, it will automatically restore the behavior of original. This value must be an integer greater than zero.
interface MockMethodOptions
Usage in Deno
import { type MockMethodOptions } from "node:test";
interface MockModuleOptions
Usage in Deno
import { type MockModuleOptions } from "node:test";
Properties
cache: boolean | undefined If false, each call to require() or import() generates a new mock module. If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache.
defaultExport: any The value to use as the mocked module's default export.
If this value is not provided, ESM mocks do not include a default export. If the mock is a CommonJS or builtin module, this setting is used as the value of module.exports. If this value is not provided, CJS and builtin mocks use an empty object as the value of module.exports.
namedExports: object | undefined An object whose keys and values are used to create the named exports of the mock module.
If the mock is a CommonJS or builtin module, these values are copied onto module.exports. Therefore, if a mock is created with both named exports and a non-object default export, the mock will throw an exception when used as a CJS or builtin module.
interface MockTimersOptions
Usage in Deno
import { type MockTimersOptions } from "node:test";
interface RunOptions
Usage in Deno
import { type RunOptions } from "node:test";
Properties
concurrency:
number
| boolean
| undefined
If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. If true, it would run os.availableParallelism() - 1 test files in parallel. If false, it would only run one test file at a time.
files: readonly string[] | undefined An array containing the list of files to run. If omitted, files are run according to the test runner execution model.
forceExit: boolean | undefined Configures the test runner to exit the process once all known tests have finished executing even if the event loop would otherwise remain active.
globPatterns: readonly string[] | undefined An array containing the list of glob patterns to match test files. This option cannot be used together with files. If omitted, files are run according to the test runner execution model.
inspectPort:
number
| (() => number)
| undefined
Sets inspector port of test child process. This can be a number, or a function that takes no arguments and returns a number. If a nullish value is provided, each process gets its own port, incremented from the primary's process.debugPort. This option is ignored if the isolation option is set to 'none' as no child processes are spawned.
isolation:
"process"
| "none"
| undefined
Configures the type of test isolation. If set to 'process', each test file is run in a separate child process. If set to 'none', all test files run in the current process.
only: boolean | undefined If truthy, the test context will only run tests that have the only option set
setup: ((reporter: TestsStream) => void | Promise<void>) | undefined A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run.
execArgv: readonly string[] | undefined An array of CLI flags to pass to the node executable when spawning the subprocesses. This option has no effect when isolation is 'none'.
argv: readonly string[] | undefined An array of CLI flags to pass to each test file when spawning the subprocesses. This option has no effect when isolation is 'none'.
signal: AbortSignal | undefined Allows aborting an in-progress test execution.
testNamePatterns:
string
| RegExp
| ReadonlyArray<string | RegExp>
| undefined
If provided, only run tests whose name matches the provided pattern. Strings are interpreted as JavaScript regular expressions.
testSkipPatterns:
string
| RegExp
| ReadonlyArray<string | RegExp>
| undefined
A String, RegExp or a RegExp Array, that can be used to exclude running tests whose name matches the provided pattern. Test name patterns are interpreted as JavaScript regular expressions. For each test that is executed, any corresponding test hooks, such as beforeEach(), are also run.
timeout: number | undefined The number of milliseconds after which the test execution will fail. If unspecified, subtests inherit this value from their parent.
watch: boolean | undefined Whether to run in watch mode or not.
coverage: boolean | undefined enable code coverage collection.
coverageExcludeGlobs:
string
| readonly string[]
| undefined
Excludes specific files from code coverage using a glob pattern, which can match both absolute and relative file paths. This property is only applicable when coverage was set to true. If both coverageExcludeGlobs and coverageIncludeGlobs are provided, files must meet both criteria to be included in the coverage report.
coverageIncludeGlobs:
string
| readonly string[]
| undefined
Includes specific files in code coverage using a glob pattern, which can match both absolute and relative file paths. This property is only applicable when coverage was set to true. If both coverageExcludeGlobs and coverageIncludeGlobs are provided, files must meet both criteria to be included in the coverage report.
lineCoverage: number | undefined Require a minimum percent of covered lines. If code coverage does not reach the threshold specified, the process will exit with code 1.
branchCoverage: number | undefined Require a minimum percent of covered branches. If code coverage does not reach the threshold specified, the process will exit with code 1.
functionCoverage: number | undefined Require a minimum percent of covered functions. If code coverage does not reach the threshold specified, the process will exit with code 1.
interface TestContextAssert
| "deepStrictEqual"
| "doesNotMatch"
| "doesNotReject"
| "doesNotThrow"
| "equal"
| "fail"
| "ifError"
| "match"
| "notDeepEqual"
| "notDeepStrictEqual"
| "notEqual"
| "notStrictEqual"
| "ok"
| "partialDeepStrictEqual"
| "rejects"
| "strictEqual"
| "throws"
Usage in Deno
import { type TestContextAssert } from "node:test";
Index Signatures
Methods
fileSnapshot(): void This function serializes value and writes it to the file specified by path.
test('snapshot test with default serialization', (t) => {
t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json');
});
This function differs from context.assert.snapshot() in the following ways:
- The snapshot file path is explicitly provided by the user.
- Each snapshot file is limited to a single snapshot value.
- No additional escaping is performed by the test runner.
These differences allow snapshot files to better support features such as syntax highlighting.
snapshot(
value: any,
options?: AssertSnapshotOptions,
): void This function implements assertions for snapshot testing.
test('snapshot test with default serialization', (t) => {
t.assert.snapshot({ value1: 1, value2: 2 });
});
test('snapshot test with custom serialization', (t) => {
t.assert.snapshot({ value3: 3, value4: 4 }, {
serializers: [(value) => JSON.stringify(value)]
});
});
interface TestContextWaitForOptions
Usage in Deno
import { type TestContextWaitForOptions } from "node:test";
interface TestOptions
Usage in Deno
import { type TestOptions } from "node:test";
Properties
concurrency:
number
| boolean
| undefined
If a number is provided, then that many tests would run in parallel. If truthy, it would run (number of cpu cores - 1) tests in parallel. For subtests, it will be Infinity tests in parallel. If falsy, it would only run one test at a time. If unspecified, subtests inherit this value from their parent.
only: boolean | undefined If truthy, and the test context is configured to run only tests, then this test will be run. Otherwise, the test is skipped.
signal: AbortSignal | undefined Allows aborting an in-progress test.
skip:
boolean
| string
| undefined
If truthy, the test is skipped. If a string is provided, that string is displayed in the test results as the reason for skipping the test.
timeout: number | undefined A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent.
todo:
boolean
| string
| undefined
If truthy, the test marked as TODO. If a string is provided, that string is displayed in the test results as the reason why the test is TODO.
plan: number | undefined The number of assertions and subtests expected to be run in the test. If the number of assertions run in the test does not match the number specified in the plan, the test will fail.
namespace assert
Usage in Deno
import { assert } from "node:test";
An object whose methods are used to configure available assertions on the TestContext objects in the current process. The methods from node:assert and snapshot testing functions are available by default.
It is possible to apply the same configuration to all files by placing common configuration code in a module preloaded with --require or --import.
Functions
Defines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
namespace default.assert
Usage in Deno
import mod from "node:test";
An object whose methods are used to configure available assertions on the TestContext objects in the current process. The methods from node:assert and snapshot testing functions are available by default.
It is possible to apply the same configuration to all files by placing common configuration code in a module preloaded with --require or --import.
Functions
Defines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
namespace default.snapshot
Usage in Deno
import mod from "node:test";
Functions
This function is used to customize the default serialization mechanism used by the test runner.
This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. By default, the snapshot filename is the same as the entry point filename with .snapshot appended.
namespace snapshot
Usage in Deno
import { snapshot } from "node:test";
Functions
This function is used to customize the default serialization mechanism used by the test runner.
This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. By default, the snapshot filename is the same as the entry point filename with .snapshot appended.
namespace test.assert
Usage in Deno
import { test } from "node:test";
An object whose methods are used to configure available assertions on the TestContext objects in the current process. The methods from node:assert and snapshot testing functions are available by default.
It is possible to apply the same configuration to all files by placing common configuration code in a module preloaded with --require or --import.
Functions
Defines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
namespace test.snapshot
Usage in Deno
import { test } from "node:test";
Functions
This function is used to customize the default serialization mechanism used by the test runner.
This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. By default, the snapshot filename is the same as the entry point filename with .snapshot appended.
type alias FunctionPropertyNames
Usage in Deno
import { type FunctionPropertyNames } from "node:test";
type alias HookFn
Usage in Deno
import { type HookFn } from "node:test";
The hook function. The first argument is the context in which the hook is called. If the hook uses callbacks, the callback function is passed as the second argument.
Definition
(
c: TestContext | SuiteContext,
done: (result?: any) => void,
) => any type alias Mock
Usage in Deno
import { type Mock } from "node:test";
Type Parameters
F extends Function Definition
F & { mock: MockFunctionContext<F>; } type alias NoOpFunction
Usage in Deno
import { type NoOpFunction } from "node:test";
Definition
(...args: any[]) => undefined type alias SuiteFn
Usage in Deno
import { type SuiteFn } from "node:test";
The type of a suite test function. The argument to this function is a SuiteContext object.
Definition
(s: SuiteContext) => void | Promise<void> type alias TestContextHookFn
Usage in Deno
import { type TestContextHookFn } from "node:test";
The hook function. The first argument is a TestContext object. If the hook uses callbacks, the callback function is passed as the second argument.
Definition
(
t: TestContext,
done: (result?: any) => void,
) => any type alias TestFn
Usage in Deno
import { type TestFn } from "node:test";
The type of a function passed to test. The first argument to this function is a TestContext object. If the test uses callbacks, the callback function is passed as the second argument.
Definition
(
t: TestContext,
done: (result?: any) => void,
) => void | Promise<void> type alias Timer
Usage in Deno
import { type Timer } from "node:test";
Definition
"setInterval"
| "setTimeout"
| "setImmediate"
| "Date"
© 2018–2025 the Deno authors
Licensed under the MIT License.
https://docs.deno.com/api/node/test