is provided directly (without wrapping in { match: … }), the test passes only if the thrown error matches, following the behavior of assert.throws . To provide both a reason and validation, pass an object with label (string) and match (RegExp, Function, Object, or Error). Default: false. only <boolean> If truthy, and the test context is configured to run only tests, then this test will be run. Otherwise, the test is skipped. Default: false. signal <AbortSignal> Allows aborting an in-progress test. skip <boolean> | <string> 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. Default: false. todo <boolean> | <string> 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. Default: false. timeout <number> A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity. plan <number> 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. Default: undefined. fn <Function> | <AsyncFunction> 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. Default: A no-op function. Returns: <Promise> Fulfilled with undefined once the test completes, or immediately if the test runs within a suite. 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 ) ;
} ) ;
} ) ;
} ) ;
copy 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.
describe([name][, options][, fn])#
Alias for suite() .
The describe() function is imported from the node:test module.
it([name][, options][, fn])# Alias for test() .
The it() function is imported from the node:test module.
before([fn][, options])# Added in: v18.8.0, v16.18.0
fn <Function> | <AsyncFunction> The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This 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' , () => {
// Some relevant assertions here
} ) ;
} ) ;
copy after([fn][, options])# Added in: v18.8.0, v16.18.0
fn <Function> | <AsyncFunction> The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This function creates a hook that runs after executing a suite.
describe ( 'tests' , async () => {
after ( () => console . log ( 'finished running tests' )) ;
it ( 'is a subtest' , () => {
// Some relevant assertion here
} ) ;
} ) ;
copy Note: The after hook is guaranteed to run, even if tests within the suite fail.
beforeEach([fn][, options])# Added in: v18.8.0, v16.18.0
fn <Function> | <AsyncFunction> The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This 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' , () => {
// Some relevant assertion here
} ) ;
} ) ;
copy afterEach([fn][, options])# Added in: v18.8.0, v16.18.0
fn <Function> | <AsyncFunction> The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This 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' , () => {
// Some relevant assertion here
} ) ;
} ) ;
copy assert# Added in: v23.7.0, v22.14.0
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.
assert.register(name, fn)# Added in: v23.7.0, v22.14.0
Defines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
snapshot# Added in: v22.3.0
An object whose methods are used to configure default snapshot settings in the current process. It is possible to apply the same configuration to all files by placing common configuration code in a module preloaded with --require or --import.
snapshot.setDefaultSnapshotSerializers(serializers)Added in: v22.3.0
serializers <Array> An array of synchronous functions used as the default serializers for snapshot tests.This 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.
snapshot.setResolveSnapshotPath(fn)# Added in: v22.3.0
fn <Function> 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 snapshot file.This function is used to customize the location of the snapshot file used for snapshot testing. By default, the snapshot filename is the same as the entry point filename with a .snapshot file extension.
Class: MockFunctionContext# Added in: v19.1.0, v18.13.0
The MockFunctionContext class is used to inspect or manipulate the behavior of mocks created via the MockTracker APIs.
ctx.calls# Added in: v19.1.0, v18.13.0
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.
arguments <Array> An array of the arguments passed to the mock function.error <any> If the mocked function threw then this property contains the thrown value. Default: undefined.result <any> The value returned by the mocked function.stack <Error> An Error object whose stack can be used to determine the callsite of the mocked function invocation.target <Function> | <undefined> If the mocked function is a constructor, this field contains the class being constructed. Otherwise this will be undefined.this <any> The mocked function’s this value. ctx.callCount()# Added in: v19.1.0, v18.13.0
Returns: <integer> The number of times that this mock has been invoked. 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.
ctx.mockImplementation(implementation)# Added in: v19.1.0, v18.13.0
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 ) ;
} ) ;
copy ctx.mockImplementationOnce(implementation[, onCall])# Added in: v19.1.0, v18.13.0
implementation <Function> | <AsyncFunction> The function to be used as the mock’s implementation for the invocation number specified by onCall.onCall <integer> The invocation number that will use implementation. If the specified invocation has already occurred then an exception is thrown. Default: The number of the next invocation.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 ) ;
} ) ;
copy ctx.resetCalls()# Added in: v19.3.0, v18.13.0
Resets the call history of the mock function.
ctx.restore()# Added in: v19.1.0, v18.13.0
Resets the implementation of the mock function to its original behavior. The mock can still be used after calling this function.
Class: MockModuleContext# Added in: v22.3.0, v20.18.0
Stability: 1.0 – Early development
The MockModuleContext class is used to manipulate the behavior of module mocks created via the MockTracker APIs.
ctx.restore()# Added in: v22.3.0, v20.18.0
Resets the implementation of the mock module.
Class: MockPropertyContext# Added in: v24.3.0, v22.20.0
The MockPropertyContext class is used to inspect or manipulate the behavior of property mocks created via the MockTracker APIs.
ctx.accesses#
A getter that returns a copy of the internal array used to track accesses (get/set) to the mocked property. Each entry in the array is an object with the following properties:
type <string> Either 'get' or 'set', indicating the type of access.value <any> The value that was read (for 'get') or written (for 'set').stack <Error> An Error object whose stack can be used to determine the callsite of the mocked function invocation. ctx.accessCount()#
Returns: <integer> The number of times that the property was accessed (read or written). This function returns the number of times that the property was accessed. This function is more efficient than checking ctx.accesses.length because ctx.accesses is a getter that creates a copy of the internal access tracking array.
ctx.mockImplementation(value)#
value <any> The new value to be set as the mocked property value.This function is used to change the value returned by the mocked property getter.
ctx.mockImplementationOnce(value[, onAccess])#
value <any> The value to be used as the mock’s implementation for the invocation number specified by onAccess.onAccess <integer> The invocation number that will use value. If the specified invocation has already occurred then an exception is thrown. Default: The number of the next invocation.This function is used to change the behavior of an existing mock for a single invocation. Once invocation onAccess 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.property(), calls the mock property, changes the mock implementation to a different value for the next invocation, and then resumes its previous behavior.
test ( 'changes a mock behavior once' , ( t ) => {
const obj = { foo : 1 };
const prop = t . mock . property (obj , 'foo' , 5 ) ;
assert . strictEqual (obj . foo , 5 ) ;
prop . mock . mockImplementationOnce ( 25 ) ;
assert . strictEqual (obj . foo , 25 ) ;
assert . strictEqual (obj . foo , 5 ) ;
} ) ;
copy Caveat#
For consistency with the rest of the mocking API, this function treats both property gets and sets as accesses. If a property set occurs at the same access index, the “once” value will be consumed by the set operation, and the mocked property value will be changed to the “once” value. This may lead to unexpected behavior if you intend the “once” value to only be used for a get operation.
ctx.resetAccesses()#
Resets the access history of the mocked property.
ctx.restore()#
Resets the implementation of the mock property to its original behavior. The mock can still be used after calling this function.
Class: MockTracker# Added in: v19.1.0, v18.13.0
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.
mock.fn([original[, implementation]][, options])# Added in: v19.1.0, v18.13.0
original <Function> | <AsyncFunction> An optional function to create a mock on. Default: A no-op function.implementation <Function> | <AsyncFunction> An optional function used as the mock implementation for original. This is useful for creating mocks that exhibit one behavior for a specified number of calls and then restore the behavior of original. Default: The function specified by original.options <Object> Optional configuration options for the mock function. The following properties are supported: times <integer> 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. Default: Infinity.Returns: <Proxy> The mocked function. The mocked function contains a special mock property, which is an instance of MockFunctionContext , and can be used for inspecting and changing the behavior of the mocked function. 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 ) ;
} ) ;
copy mock.getter(object, methodName[, implementation][, options])# Added in: v19.3.0, v18.13.0
This function is syntax sugar for MockTracker.method with options.getter set to true.
mock.method(object, methodName[, implementation][, options])# Added in: v19.1.0, v18.13.0
object <Object> The object whose method is being mocked.methodName <string> | <symbol> The identifier of the method on object to mock. If object[methodName] is not a function, an error is thrown.implementation <Function> | <AsyncFunction> An optional function used as the mock implementation for object[methodName]. Default: The original method specified by object[methodName].options <Object> Optional configuration options for the mock method. The following properties are supported: getter <boolean> If true, object[methodName] is treated as a getter. This option cannot be used with the setter option. Default: false.setter <boolean> If true, object[methodName] is treated as a setter. This option cannot be used with the getter option. Default: false.times <integer> The number of times that the mock will use the behavior of implementation. Once the mocked method has been called times times, it will automatically restore the original behavior. This value must be an integer greater than zero. Default: Infinity.Returns: <Proxy> The mocked method. The mocked method contains a special mock property, which is an instance of MockFunctionContext , and can be used for inspecting and changing the behavior of the mocked method. 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 . callCount () , 0 ) ;
assert . strictEqual (number . subtract ( 3 ) , 2 ) ;
assert . strictEqual (number . subtract . mock . callCount () , 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) ;
} ) ;
copy mock.module(specifier[, options])# Stability: 1.0 – Early development
specifier <string> | <URL> A string identifying the module to mock.options <Object> Optional configuration options for the mock module. The following properties are supported: cache <boolean> 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. Default: false.defaultExport <any> An optional value used 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> An optional 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.Returns: <MockModuleContext> An object that can be used to manipulate the mock. This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In order to enable module mocking, Node.js must be started with the --experimental-test-module-mocks command-line flag.
The following example demonstrates how a mock is created for a module.
test ( 'mocks a builtin module in both module systems' , async ( t ) => {
// Create a mock of 'node:readline' with a named export named 'fn', which
// does not exist in the original 'node:readline' module.
const mock = t . mock . module ( 'node:readline' , {
namedExports : { fn () { return 42 ; } },
} ) ;
let esmImpl = await import ( 'node:readline' ) ;
let cjsImpl = require ( 'node:readline' ) ;
// cursorTo() is an export of the original 'node:readline' module.
assert . strictEqual (esmImpl . cursorTo , undefined ) ;
assert . strictEqual (cjsImpl . cursorTo , undefined ) ;
assert . strictEqual (esmImpl . fn () , 42 ) ;
assert . strictEqual (cjsImpl . fn () , 42 ) ;
mock . restore () ;
// The mock is restored, so the original builtin module is returned.
esmImpl = await import ( 'node:readline' ) ;
cjsImpl = require ( 'node:readline' ) ;
assert . strictEqual ( typeof esmImpl . cursorTo , 'function' ) ;
assert . strictEqual ( typeof cjsImpl . cursorTo , 'function' ) ;
assert . strictEqual (esmImpl . fn , undefined ) ;
assert . strictEqual (cjsImpl . fn , undefined ) ;
} ) ;
copy mock.property(object, propertyName[, value])# Added in: v24.3.0, v22.20.0
object <Object> The object whose value is being mocked.propertyName <string> | <symbol> The identifier of the property on object to mock.value <any> An optional value used as the mock value for object[propertyName]. Default: The original property value.Returns: <Proxy> A proxy to the mocked object. The mocked object contains a special mock property, which is an instance of MockPropertyContext , and can be used for inspecting and changing the behavior of the mocked property. Creates a mock for a property value on an object. This allows you to track and control access to a specific property, including how many times it is read (getter) or written (setter), and to restore the original value after mocking.
test ( 'mocks a property value' , ( t ) => {
const obj = { foo : 42 };
const prop = t . mock . property (obj , 'foo' , 100 ) ;
assert . strictEqual (obj . foo , 100 ) ;
assert . strictEqual (prop . mock . accessCount () , 1 ) ;
assert . strictEqual (prop . mock . accesses[ 0 ] . type , 'get' ) ;
assert . strictEqual (prop . mock . accesses[ 0 ] . value , 100 ) ;
obj . foo = 200 ;
assert . strictEqual (prop . mock . accessCount () , 2 ) ;
assert . strictEqual (prop . mock . accesses[ 1 ] . type , 'set' ) ;
assert . strictEqual (prop . mock . accesses[ 1 ] . value , 200 ) ;
prop . mock . restore () ;
assert . strictEqual (obj . foo , 42 ) ;
} ) ;
copy mock.reset()# Added in: v19.1.0, v18.13.0
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.
mock.restoreAll()# Added in: v19.1.0, v18.13.0
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.
mock.setter(object, methodName[, implementation][, options])# Added in: v19.3.0, v18.13.0
This function is syntax sugar for MockTracker.method with options.setter set to true.
Class: MockTimers# 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.
MockTimers is also able to mock the Date object.
The MockTracker provides a top-level timers export which is a MockTimers instance.
timers.enable([enableOptions])# Enables timer mocking for the specified timers.
enableOptions <Object> Optional configuration options for enabling timer mocking. The following properties are supported: apis <Array> An optional array containing the timers to mock. The currently supported timer values are 'setInterval', 'setTimeout', 'setImmediate', and 'Date'. Default: ['setInterval', 'setTimeout', 'setImmediate', 'Date']. If no array is provided, all time related APIs ('setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'setImmediate', 'clearImmediate', and 'Date') will be mocked by default.now <number> | <Date> An optional number or Date object representing the initial time (in milliseconds) to use as the value for Date.now(). Default: 0.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' ] } ) ;
const { mock } = require ( 'node:test' ) ;
mock . timers . enable ( { apis : [ 'setInterval' ] } ) ;
copy The above example enables mocking for the setInterval timer and implicitly mocks the clearInterval function. Only the 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 } ) ;
const { mock } = require ( 'node:test' ) ;
mock . timers . enable ( { apis : [ 'Date' ] , now : 1000 } ) ;
copy Example usage with initial Date object as time set
import { mock } from 'node:test' ;
mock . timers . enable ( { apis : [ 'Date' ] , now : new Date () } ) ;
const { mock } = require ( 'node:test' ) ;
mock . timers . enable ( { apis : [ 'Date' ] , now : new Date () } ) ;
copy Alternatively, if you call mock.timers.enable() without any parameters:
All timers ('setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'setImmediate', and 'clearImmediate') will be mocked. The setInterval, clearInterval, setTimeout, clearTimeout, setImmediate, and clearImmediate functions from node:timers, node:timers/promises, and globalThis will be mocked. As well as the global Date object.
timers.reset()# Added in: v20.4.0, v18.19.0
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 () ;
const { mock } = require ( 'node:test' ) ;
mock . timers . reset () ;
copy timers[Symbol.dispose]()
Calls timers.reset().
timers.tick([milliseconds])# Added in: v20.4.0, v18.19.0
Advances time for all mocked timers.
milliseconds <number> The amount of time, in milliseconds, to advance the timers. Default: 1.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 ) ;
} ) ;
const assert = require ( 'node:assert' ) ;
const { test } = require ( '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 ) ;
} ) ;
copy Alternatively, 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 threeSeconds = 3000 ;
context . mock . timers . tick (threeSeconds) ;
context . mock . timers . tick (threeSeconds) ;
context . mock . timers . tick (threeSeconds) ;
assert . strictEqual (fn . mock . callCount () , 1 ) ;
} ) ;
const assert = require ( 'node:assert' ) ;
const { test } = require ( '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 threeSeconds = 3000 ;
context . mock . timers . tick (threeSeconds) ;
context . mock . timers . tick (threeSeconds) ;
context . mock . timers . tick (threeSeconds) ;
assert . strictEqual (fn . mock . callCount () , 1 ) ;
} ) ;
copy 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 ) ;
} ) ;
const assert = require ( 'node:assert' ) ;
const { test } = require ( '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 ) ;
} ) ;
copy Working with Node.js timers modules#
Once you enable mocking timers, node:timers , node:timers/promises modules, and timers from the Node.js global context are enabled:
Note: Destructuring functions such as import { setTimeout } from 'node:timers' is currently not supported by this API.
import assert from 'node:assert' ;
import { test } from 'node:test' ;
import nodeTimers from 'node:timers' ;
import nodeTimersPromises from 'node:timers/promises' ;
test ( 'mocks setTimeout to be executed synchronously without having to actually wait for it' , async ( context ) => {
const globalTimeoutObjectSpy = context . mock . fn () ;
const nodeTimerSpy = context . mock . fn () ;
const nodeTimerPromiseSpy = context . mock . fn () ;
// Optionally choose what to mock
context . mock . timers . enable ( { apis : [ 'setTimeout' ] } ) ;
setTimeout (globalTimeoutObjectSpy , 9999 ) ;
nodeTimers . setTimeout (nodeTimerSpy , 9999 ) ;
const promise = nodeTimersPromises . setTimeout ( 9999 ) . then (nodeTimerPromiseSpy) ;
// Advance in time
context . mock . timers . tick ( 9999 ) ;
assert . strictEqual (globalTimeoutObjectSpy . mock . callCount () , 1 ) ;
assert . strictEqual (nodeTimerSpy . mock . callCount () , 1 ) ;
await promise ;
assert . strictEqual (nodeTimerPromiseSpy . mock . callCount () , 1 ) ;
} ) ;
const assert = require ( 'node:assert' ) ;
const { test } = require ( 'node:test' ) ;
const nodeTimers = require ( 'node:timers' ) ;
const nodeTimersPromises = require ( 'node:timers/promises' ) ;
test ( 'mocks setTimeout to be executed synchronously without having to actually wait for it' , async ( context ) => {
const globalTimeoutObjectSpy = context . mock . fn () ;
const nodeTimerSpy = context . mock . fn () ;
const nodeTimerPromiseSpy = context . mock . fn () ;
// Optionally choose what to mock
context . mock . timers . enable ( { apis : [ 'setTimeout' ] } ) ;
setTimeout (globalTimeoutObjectSpy , 9999 ) ;
nodeTimers . setTimeout (nodeTimerSpy , 9999 ) ;
const promise = nodeTimersPromises . setTimeout ( 9999 ) . then (nodeTimerPromiseSpy) ;
// Advance in time
context . mock . timers . tick ( 9999 ) ;
assert . strictEqual (globalTimeoutObjectSpy . mock . callCount () , 1 ) ;
assert . strictEqual (nodeTimerSpy . mock . callCount () , 1 ) ;
await promise ;
assert . strictEqual (nodeTimerPromiseSpy . mock . callCount () , 1 ) ;
} ) ;
copy In Node.js, setInterval from node:timers/promises is an AsyncGenerator and is also supported by this API:
import assert from 'node:assert' ;
import { test } from 'node:test' ;
import nodeTimersPromises from 'node:timers/promises' ;
test ( 'should tick five times testing a real use case' , async ( context ) => {
context . mock . timers . enable ( { apis : [ 'setInterval' ] } ) ;
const expectedIterations = 3 ;
const interval = 1000 ;
const startedAt = Date . now () ;
async function run () {
const times = [] ;
for await ( const time of nodeTimersPromises . setInterval (interval , startedAt)) {
times . push (time) ;
if (times . length === expectedIterations) break ;
}
return times ;
}
const r = run () ;
context . mock . timers . tick (interval) ;
context . mock . timers . tick (interval) ;
context . mock . timers . tick (interval) ;
const timeResults = await r ;
assert . strictEqual (timeResults . length , expectedIterations) ;
for ( let it = 1 ; it < expectedIterations ; it ++ ) {
assert . strictEqual (timeResults[it - 1 ] , startedAt + (interval * it)) ;
}
} ) ;
const assert = require ( 'node:assert' ) ;
const { test } = require ( 'node:test' ) ;
const nodeTimersPromises = require ( 'node:timers/promises' ) ;
test ( 'should tick five times testing a real use case' , async ( context ) => {
context . mock . timers . enable ( { apis : [ 'setInterval' ] } ) ;
const expectedIterations = 3 ;
const interval = 1000 ;
const startedAt = Date . now () ;
async function run () {
const times = [] ;
for await ( const time of nodeTimersPromises . setInterval (interval , startedAt)) {
times . push (time) ;
if (times . length === expectedIterations) break ;
}
return times ;
}
const r = run () ;
context . mock . timers . tick (interval) ;
context . mock . timers . tick (interval) ;
context . mock . timers . tick (interval) ;
const timeResults = await r ;
assert . strictEqual (timeResults . length , expectedIterations) ;
for ( let it = 1 ; it < expectedIterations ; it ++ ) {
assert . strictEqual (timeResults[it - 1 ] , startedAt + (interval * it)) ;
}
} ) ;
copy timers.runAll()# Added in: v20.4.0, v18.19.0
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 ) ;
} ) ;
const assert = require ( 'node:assert' ) ;
const { test } = require ( '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 ) ;
} ) ;
copy 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.
Dates and Timers working together#
Dates and timer objects are dependent on each other. If you use setTime() to pass the current time to the mocked Date object, the set timers with setTimeout and setInterval will not be affected.
However, the tick method will advance the mocked Date object.
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 ) ;
assert . deepStrictEqual (results , []) ;
context . mock . timers . setTime ( 12000 ) ;
assert . deepStrictEqual (results , []) ;
// The date is advanced but the timers don't tick
assert . strictEqual (Date . now () , 12000 ) ;
} ) ;
const assert = require ( 'node:assert' ) ;
const { test } = require ( 'node:test' ) ;
test ( 'runAll functions following the given order' , ( context ) => {
context . mock . timers . enable ( { apis : [ 'setTimeout' , 'Date' ] } ) ;
const results = [] ;
setTimeout ( () => results . push ( 1 ) , 9999 ) ;
assert . deepStrictEqual (results , []) ;
context . mock . timers . setTime ( 12000 ) ;
assert . deepStrictEqual (results , []) ;
// The date is advanced but the timers don't tick
assert . strictEqual (Date . now () , 12000 ) ;
} ) ;
copy Class: TestsStream# A successful call to run() method will return a new <TestsStream> object, streaming a series of events representing the execution of the tests. TestsStream will emit events, in the order of the tests definition
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.
Event: 'test:coverage'#
data <Object> summary <Object> An object containing the coverage report. files <Array> An array of coverage reports for individual files. Each report is an object with the following schema: path <string> The absolute path of the file.totalLineCount <number> The total number of lines.totalBranchCount <number> The total number of branches.totalFunctionCount <number> The total number of functions.coveredLineCount <number> The number of covered lines.coveredBranchCount <number> The number of covered branches.coveredFunctionCount <number> The number of covered functions.coveredLinePercent <number> The percentage of lines covered.coveredBranchPercent <number> The percentage of branches covered.coveredFunctionPercent <number> The percentage of functions covered.functions <Array> An array of functions representing function coverage. name <string> The name of the function.line <number> The line number where the function is defined.count <number> The number of times the function was called.branches <Array> An array of branches representing branch coverage. line <number> The line number where the branch is defined.count <number> The number of times the branch was taken.lines <Array> An array of lines representing line numbers and the number of times they were covered. line <number> The line number.count <number> The number of times the line was covered.thresholds <Object> An object containing whether or not the coverage for each coverage type. function <number> The function coverage threshold.branch <number> The branch coverage threshold.line <number> The line coverage threshold.totals <Object> An object containing a summary of coverage for all files. totalLineCount <number> The total number of lines.totalBranchCount <number> The total number of branches.totalFunctionCount <number> The total number of functions.coveredLineCount <number> The number of covered lines.coveredBranchCount <number> The number of covered branches.coveredFunctionCount <number> The number of covered functions.coveredLinePercent <number> The percentage of lines covered.coveredBranchPercent <number> The percentage of branches covered.coveredFunctionPercent <number> The percentage of functions covered.workingDirectory <string> The working directory when code coverage began. This is useful for displaying relative path names in case the tests changed the working directory of the Node.js process.nesting <number> The nesting level of the test.Emitted when code coverage is enabled and all tests have completed.
Event: 'test:complete'#
Emitted when a test completes its execution. This event is not emitted in the same order as the tests are defined. The corresponding declaration ordered events are 'test:pass' and 'test:fail'.
Event: 'test:dequeue'#
data <Object> column <number> | <undefined> The column number where the test is defined, or undefined if the test was run through the REPL.file <string> | <undefined> The path of the test file, undefined if test was run through the REPL.line <number> | <undefined> The line number where the test is defined, or undefined if the test was run through the REPL.name <string> The test name.nesting <number> The nesting level of the test.type <string> The test type. Either 'suite' or 'test'.Emitted when a test is dequeued, right before it is executed. This event is not guaranteed to be emitted in the same order as the tests are defined. The corresponding declaration ordered event is 'test:start'.
Event: 'test:diagnostic'#
data <Object> column <number> | <undefined> The column number where the test is defined, or undefined if the test was run through the REPL.file <string> | <undefined> The path of the test file, undefined if test was run through the REPL.line <number> | <undefined> The line number where the test is defined, or undefined if the test was run through the REPL.message <string> The diagnostic message.nesting <number> The nesting level of the test.level <string> The severity level of the diagnostic message. Possible values are: 'info': Informational messages.'warn': Warnings.'error': Errors.Emitted when context.diagnostic is called. This event is guaranteed to be emitted in the same order as the tests are defined.
Event: 'test:enqueue'#
data <Object> column <number> | <undefined> The column number where the test is defined, or undefined if the test was run through the REPL.file <string> | <undefined> The path of the test file, undefined if test was run through the REPL.line <number> | <undefined> The line number where the test is defined, or undefined if the test was run through the REPL.name <string> The test name.nesting <number> The nesting level of the test.type <string> The test type. Either 'suite' or 'test'.Emitted when a test is enqueued for execution.
Event: 'test:fail'#
Emitted when a test fails. This event is guaranteed to be emitted in the same order as the tests are defined. The corresponding execution ordered event is 'test:complete'.
Event: 'test:interrupted'# Added in: v25.7.0
data <Object> tests <Array> An array of objects containing information about the interrupted tests. column <number> | <undefined> The column number where the test is defined, or undefined if the test was run through the REPL.file <string> | <undefined> The path of the test file, undefined if test was run through the REPL.line <number> | <undefined> The line number where the test is defined, or undefined if the test was run through the REPL.name <string> The test name.nesting <number> The nesting level of the test.Emitted when the test runner is interrupted by a SIGINT signal (e.g., when pressing Ctrl +C ). The event contains information about the tests that were running at the time of interruption.
When using process isolation (the default), the test name will be the file path since the parent runner only knows about file-level tests. When using --test-isolation=none, the actual test name is shown.
Event: 'test:pass'#
Emitted when a test passes. This event is guaranteed to be emitted in the same order as the tests are defined. The corresponding execution ordered event is 'test:complete'.
Event: 'test:plan'#
data <Object> column <number> | <undefined> The column number where the test is defined, or undefined if the test was run through the REPL.file <string> | <undefined> The path of the test file, undefined if test was run through the REPL.line <number> | <undefined> The line number where the test is defined, or undefined if the test was run through the REPL.nesting <number> The nesting level of the test.count <number> The number of subtests that have ran.Emitted when all subtests have completed for a given test. This event is guaranteed to be emitted in the same order as the tests are defined.
Event: 'test:start'#
data <Object> column <number> | <undefined> The column number where the test is defined, or undefined if the test was run through the REPL.file <string> | <undefined> The path of the test file, undefined if test was run through the REPL.line <number> | <undefined> The line number where the test is defined, or undefined if the test was run through the REPL.name <string> The test name.nesting <number> The nesting level of the test.Emitted when a test starts reporting its own and its subtests status. This event is guaranteed to be emitted in the same order as the tests are defined. The corresponding execution ordered event is 'test:dequeue'.
Event: 'test:stderr'#
Emitted when a running test writes to stderr. This event is only emitted if --test flag is passed. This event is not guaranteed to be emitted in the same order as the tests are defined.
Event: 'test:stdout'#
Emitted when a running test writes to stdout. This event is only emitted if --test flag is passed. This event is not guaranteed to be emitted in the same order as the tests are defined.
Event: 'test:summary'#
data <Object> counts <Object> An object containing the counts of various test results. cancelled <number> The total number of cancelled tests.failed <number> The total number of failed tests.passed <number> The total number of passed tests.skipped <number> The total number of skipped tests.suites <number> The total number of suites run.tests <number> The total number of tests run, excluding suites.todo <number> The total number of TODO tests.topLevel <number> The total number of top level tests and suites.duration_ms <number> The duration of the test run in milliseconds.file <string> | <undefined> The path of the test file that generated the summary. If the summary corresponds to multiple files, this value is undefined.success <boolean> Indicates whether or not the test run is considered successful or not. If any error condition occurs, such as a failing test or unmet coverage threshold, this value will be set to false.Emitted when a test run completes. This event contains metrics pertaining to the completed test run, and is useful for determining if a test run passed or failed. If process-level test isolation is used, a 'test:summary' event is generated for each test file in addition to a final cumulative summary.
Event: 'test:watch:drained'#
Emitted when no more tests are queued for execution in watch mode.
Event: 'test:watch:restarted'#
Emitted when one or more tests are restarted due to a file change in watch mode.
Class: TestContext# 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.
context.before([fn][, options])# Added in: v20.1.0, v18.17.0
fn <Function> | <AsyncFunction> The hook function. The first argument to this function is a TestContext object. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This function is used to create a hook running before subtest of the current test.
context.beforeEach([fn][, options])# Added in: v18.8.0, v16.18.0
fn <Function> | <AsyncFunction> The hook function. The first argument to this function is a TestContext object. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This function is used to create a hook running before each subtest of the current test.
test ( 'top level test' , async ( t ) => {
t . beforeEach ( ( t ) => t . diagnostic ( `about to run ${ t . name } ` )) ;
await t . test (
'This is a subtest' ,
( t ) => {
// Some relevant assertion here
},
) ;
} ) ;
copy context.after([fn][, options])# Added in: v19.3.0, v18.13.0
fn <Function> | <AsyncFunction> The hook function. The first argument to this function is a TestContext object. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This function is used to create a hook that runs after the current test finishes.
test ( 'top level test' , async ( t ) => {
t . after ( ( t ) => t . diagnostic ( `finished running ${ t . name } ` )) ;
// Some relevant assertion here
} ) ;
copy context.afterEach([fn][, options])# Added in: v18.8.0, v16.18.0
fn <Function> | <AsyncFunction> The hook function. The first argument to this function is a TestContext object. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.options <Object> Configuration options for the hook. The following properties are supported: signal <AbortSignal> Allows aborting an in-progress hook.timeout <number> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.This function is used to create a hook running after each subtest of the current test.
test ( 'top level test' , async ( t ) => {
t . afterEach ( ( t ) => t . diagnostic ( `finished running ${ t . name } ` )) ;
await t . test (
'This is a subtest' ,
( t ) => {
// Some relevant assertion here
},
) ;
} ) ;
copy context.assert# Added in: v22.2.0, v20.15.0
An object containing assertion methods bound to context. The top-level functions from the node:assert module are exposed here for the purpose of creating test plans.
test ( 'test' , ( t ) => {
t . plan ( 1 ) ;
t . assert . strictEqual ( true , true ) ;
} ) ;
copy context.assert.fileSnapshot(value, path[, options])# Added in: v23.7.0, v22.14.0
value <any> A value to serialize to a string. If Node.js was started with the --test-update-snapshots flag, the serialized value is written to path. Otherwise, the serialized value is compared to the contents of the existing snapshot file.path <string> The file where the serialized value is written.options <Object> Optional configuration options. The following properties are supported: serializers <Array> 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. Default: If no serializers are provided, the test runner’s default serializers are used.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' ) ;
} ) ;
copy 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.
context.assert.snapshot(value[, options])# Added in: v22.3.0
value <any> A value to serialize to a string. If Node.js was started with the --test-update-snapshots flag, the serialized value is written to the snapshot file. Otherwise, the serialized value is compared to the corresponding value in the existing snapshot file.options <Object> Optional configuration options. The following properties are supported: serializers <Array> 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. Default: If no serializers are provided, the test runner’s default serializers are used.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)] ,
} ) ;
} ) ;
copy context.diagnostic(message)# Added in: v18.0.0, v16.17.0
message <string> Message to be reported.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' ) ;
} ) ;
copy context.filePath# Added in: v22.6.0, v20.16.0
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.
context.fullName# Added in: v22.3.0, v20.16.0
The name of the test and each of its ancestors, separated by >.
context.name# Added in: v18.8.0, v16.18.0
The name of the test.
context.passed# Added in: v21.7.0, v20.12.0
Type: <boolean> false before the test is executed, e.g. in a beforeEach hook. Indicated whether the test succeeded.
context.error# Added in: v21.7.0, v20.12.0
The failure reason for the test/case; wrapped and available via context.error.cause.
context.attempt# Added in: v25.0.0
Number of times the test has been attempted.
context.workerId# Added in: v25.8.0
The unique identifier of the worker running the current test file. This value is derived from the NODE_TEST_WORKER_ID environment variable. When running tests with --test-isolation=process (the default), each test file runs in a separate child process and is assigned a worker ID from 1 to N, where N is the number of concurrent workers. When running with --test-isolation=none, all tests run in the same process and the worker ID is always 1. This value is undefined when not running in a test context.
This property is useful for splitting resources (like database connections or server ports) across concurrent test files:
import { test } from 'node:test' ;
import { process } from 'node:process' ;
test ( 'database operations' , async ( t ) => {
// Worker ID is available via context
console . log ( `Running in worker ${ t . workerId } ` ) ;
// Or via environment variable (available at import time)
const workerId = process . env . NODE_TEST_WORKER_ID ;
// Use workerId to allocate separate resources per worker
} ) ;
copy context.plan(count[,options])# count <number> The number of assertions and subtests that are expected to run.options <Object> Additional options for the plan. wait <boolean> | <number> The wait time for the plan: If true, the plan waits indefinitely for all assertions and subtests to run. If false, the plan performs an immediate check after the test function completes, without waiting for any pending assertions or subtests. Any assertions or subtests that complete after this check will not be counted towards the plan. If a number, it specifies the maximum wait time in milliseconds before timing out while waiting for expected assertions and subtests to be matched. If the timeout is reached, the test will fail. Default: false. This function is 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.
Note: To make sure assertions are tracked, t.assert must be used instead of assert directly.
test ( 'top level test' , ( t ) => {
t . plan ( 2 ) ;
t . assert . ok ( 'some relevant assertion here' ) ;
t . test ( 'subtest' , () => {} ) ;
} ) ;
copy 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 () ;
} ) ;
} ) ;
copy When using the wait option, you can control how long the test will wait for the expected assertions. For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions to complete within the specified timeframe:
test ( 'plan with wait: 2000 waits for async assertions' , ( t ) => {
t . plan ( 1 , { wait : 2000 } ) ; // Waits for up to 2 seconds for the assertion to complete.
const asyncActivity = () => {
setTimeout ( () => {
t . assert . ok ( true , 'Async assertion completed within the wait time' ) ;
}, 1000 ) ; // Completes after 1 second, within the 2-second wait time.
};
asyncActivity () ; // The test will pass because the assertion is completed in time.
} ) ;
copy Note: If a wait timeout is specified, it begins counting down only after the test function finishes executing.
context.runOnly(shouldRunOnlyTests)# Added in: v18.0.0, v16.17.0
shouldRunOnlyTests <boolean> Whether or not to run only tests.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 } ) ,
]) ;
} ) ;
copy context.signal# Added in: v18.7.0, v16.17.0
Can be used to abort test subtasks when the test has been aborted.
test ( 'top level test' , async ( t ) => {
await fetch ( 'some/uri' , { signal : t . signal } ) ;
} ) ;
copy context.skip([message])# Added in: v18.0.0, v16.17.0
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' ) ;
} ) ;
copy context.todo([message])# Added in: v18.0.0, v16.17.0
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' ) ;
} ) ;
copy context.test([name][, options][, fn])# name <string> The name of the subtest, which is displayed when reporting test results. Default: The name property of fn, or '<anonymous>' if fn does not have a name.options <Object> Configuration options for the subtest. The following properties are supported: concurrency <number> | <boolean> | <null> If a number is provided, then that many tests would run asynchronously (they are still managed by the single-threaded event loop). If true, it would run all subtests in parallel. If false, it would only run one test at a time. If unspecified, subtests inherit this value from their parent. Default: null.only <boolean> If truthy, and the test context is configured to run only tests, then this test will be run. Otherwise, the test is skipped. Default: false.signal <AbortSignal> Allows aborting an in-progress test.skip <boolean> | <string> 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. Default: false.todo <boolean> | <string> 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. Default: false.timeout <number> A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.plan <number> 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. Default: undefined.fn <Function> | <AsyncFunction> 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. Default: A no-op function.Returns: <Promise> Fulfilled with undefined once the test completes. This function is used to create subtests under the current test. This function behaves in the same fashion as the top level test() function.
test ( 'top level test' , async ( t ) => {
await t . test (
'This is a subtest' ,
{ only : false , skip : false , concurrency : 1 , todo : false , plan : 1 },
( t ) => {
t . assert . ok ( 'some relevant assertion here' ) ;
},
) ;
} ) ;
copy context.waitFor(condition[, options])# Added in: v23.7.0, v22.14.0
condition <Function> | <AsyncFunction> An assertion function that is invoked periodically until it completes successfully or the defined polling timeout elapses. Successful completion is defined as not throwing or rejecting. This function does not accept any arguments, and is allowed to return any value.options <Object> An optional configuration object for the polling operation. The following properties are supported: interval <number> The number of milliseconds to wait after an unsuccessful invocation of condition before trying again. Default: 50.timeout <number> The poll timeout in milliseconds. If condition has not succeeded by the time this elapses, an error occurs. Default: 1000.Returns: <Promise> Fulfilled with the value returned by condition. This method polls a condition function until that function either returns successfully or the operation times out.
Class: SuiteContext# Added in: v18.7.0, v16.17.0
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.
context.filePath# Added in: v22.6.0
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.
context.fullName# Added in: v22.3.0, v20.16.0
The name of the suite and each of its ancestors, separated by >.
context.name# Added in: v18.8.0, v16.18.0
The name of the suite.
context.signal# Added in: v18.7.0, v16.17.0
Can be used to abort test subtasks when the test has been aborted.