namespace
test.default
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.
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.
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.
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);
});
});
});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.
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.
Configuration options for the test.
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.
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);
});
});
});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.
Configuration options for the test.
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.
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);
});
});
});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.
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.
Fulfilled with undefined once the test completes, or immediately if the test runs within a suite.
namespace assert
An object whose methods are used to configure available assertions on the
TestContextobjects in the current process. The methods fromnode:assertand 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
--requireor--import.- name: string,): void;
Defines a new assertion function with the provided name and function. If an assertion already exists with the same name, it is overwritten.
namespace EventData
interface LocationInfo
interface TestComplete
- column?: number
The column number where the test is defined, or
undefinedif the test was run through the REPL. - line?: number
The line number where the test is defined, or
undefinedif the test was run through the REPL. - testId: number
A numeric identifier for this test instance, unique within the test file's process. Consistent across all events for the same test instance, enabling reliable correlation in custom reporters.
interface TestCoverage
- summary: { files: { branches: { count: number; line: number }[]; coveredBranchCount: number; coveredBranchPercent: number; coveredFunctionCount: number; coveredFunctionPercent: number; coveredLineCount: number; coveredLinePercent: number; functions: { count: number; line: number; name: string }[]; lines: { count: number; line: number }[]; path: string; totalBranchCount: number; totalFunctionCount: number; totalLineCount: number }[]; thresholds: { branch: number; function: number; line: number }; totals: { coveredBranchCount: number; coveredBranchPercent: number; coveredFunctionCount: number; coveredFunctionPercent: number; coveredLineCount: number; coveredLinePercent: number; totalBranchCount: number; totalFunctionCount: number; totalLineCount: number }; workingDirectory: string }
An object containing the coverage report.
interface TestDequeue
- column?: number
The column number where the test is defined, or
undefinedif the test was run through the REPL. - line?: number
The line number where the test is defined, or
undefinedif the test was run through the REPL. - testId: number
A numeric identifier for this test instance, unique within the test file's process. Consistent across all events for the same test instance, enabling reliable correlation in custom reporters.
interface TestDiagnostic
- column?: number
The column number where the test is defined, or
undefinedif the test was run through the REPL. - level: 'error' | 'info' | 'warn'
The severity level of the diagnostic message. Possible values are:
'info': Informational messages.'warn': Warnings.'error': Errors.
- line?: number
The line number where the test is defined, or
undefinedif the test was run through the REPL.
interface TestEnqueue
- column?: number
The column number where the test is defined, or
undefinedif the test was run through the REPL. - line?: number
The line number where the test is defined, or
undefinedif the test was run through the REPL. - testId: number
A numeric identifier for this test instance, unique within the test file's process. Consistent across all events for the same test instance, enabling reliable correlation in custom reporters.
interface TestFail
- column?: number
The column number where the test is defined, or
undefinedif the test was run through the REPL. - line?: number
The line number where the test is defined, or
undefinedif the test was run through the REPL. - testId: number
A numeric identifier for this test instance, unique within the test file's process. Consistent across all events for the same test instance, enabling reliable correlation in custom reporters.
interface TestInterrupted
interface TestPass
- column?: number
The column number where the test is defined, or
undefinedif the test was run through the REPL. - details: { attempt: number; duration_ms: number; passed_on_attempt: number; type: 'suite' | 'test' }
Additional execution metadata.
- line?: number
The line number where the test is defined, or
undefinedif the test was run through the REPL. - testId: number
A numeric identifier for this test instance, unique within the test file's process. Consistent across all events for the same test instance, enabling reliable correlation in custom reporters.
interface TestPlan
interface TestStart
- column?: number
The column number where the test is defined, or
undefinedif the test was run through the REPL. - line?: number
The line number where the test is defined, or
undefinedif the test was run through the REPL. - testId: number
A numeric identifier for this test instance, unique within the test file's process. Consistent across all events for the same test instance, enabling reliable correlation in custom reporters.
interface TestStderr
interface TestStdout
interface TestSummary
- counts: { cancelled: number; passed: number; skipped: number; suites: number; tests: number; todo: number; topLevel: number }
An object containing the counts of various test results.
- file: undefined | string
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.
namespace snapshot
- serializers: readonly (value: any) => any[]): void;
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 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.
@param serializersAn array of synchronous functions used as the default serializers for snapshot tests.
- fn: (path: undefined | string) => string): void;
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
.snapshotappended.@param fnA 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.
- name?: string,): Promise<void>;
The
suite()function is imported from thenode:testmodule.@param nameThe name of the suite, which is displayed when reporting test results. Defaults to the
nameproperty offn, or'<anonymous>'iffndoes not have a name.@param optionsConfiguration options for the suite. This supports the same options as test.
@param fnThe suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
@returnsImmediately fulfilled with
undefined.name?: string,): Promise<void>;The
suite()function is imported from thenode:testmodule.@param nameThe name of the suite, which is displayed when reporting test results. Defaults to the
nameproperty offn, or'<anonymous>'iffndoes not have a name.@param fnThe suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
@returnsImmediately fulfilled with
undefined.): Promise<void>;The
suite()function is imported from thenode:testmodule.@param optionsConfiguration options for the suite. This supports the same options as test.
@param fnThe suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
@returnsImmediately fulfilled with
undefined.namespace suite
- name?: string,): Promise<void>;
This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
name?: string,): Promise<void>;This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
): Promise<void>;This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
): Promise<void>;This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
- name?: string,): Promise<void>;
Shorthand for marking a suite as
only. This is the same as calling suite withoptions.onlyset totrue.): Promise<void>;Shorthand for marking a suite as
only. This is the same as calling suite withoptions.onlyset totrue. - name?: string,): Promise<void>;
Shorthand for skipping a suite. This is the same as calling suite with
options.skipset totrue.): Promise<void>;Shorthand for skipping a suite. This is the same as calling suite with
options.skipset totrue. - name?: string,): Promise<void>;
Shorthand for marking a suite as
TODO. This is the same as calling suite withoptions.todoset totrue.): Promise<void>;Shorthand for marking a suite as
TODO. This is the same as calling suite withoptions.todoset totrue.
class MockPropertyContext<PropertyType = any>
This function returns the number of times that the property was accessed. This function is more efficient than checking
ctx.accesses.lengthbecausectx.accessesis a getter that creates a copy of the internal access tracking array.@returnsThe number of times that the property was accessed (read or written).
- value: PropertyType): void;
This function is used to change the value returned by the mocked property getter.
@param valueThe new value to be set as the mocked property value.
- value: PropertyType,onAccess?: number): void;
This function is used to change the behavior of an existing mock for a single invocation. Once invocation
onAccesshas occurred, the mock will revert to whatever behavior it would have used hadmockImplementationOnce()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); });@param valueThe value to be used as the mock's implementation for the invocation number specified by
onAccess.@param onAccessThe 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. Resets the access history of the mocked property.
Resets the implementation of the mock property to its original behavior. The mock can still be used after calling this function.
interface AssertSnapshotOptions
- serializers?: readonly (value: any) => any[]
An array of synchronous functions used to serialize
valueinto a string.valueis 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
Configuration options for hooks.
- timeout?: number
A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent.
interface MockFunctionCall<F extends Function, ReturnType = F extends (...args: any) => infer T ? T : F extends new (...args: any) => infer T ? T : unknown, Args = F extends (...args: infer Y) => any ? Y : F extends new (...args: infer Y) => any ? Y : unknown[]>
- result: undefined | ReturnType
The value returned by the mocked function.
If the mocked function threw, it will be
undefined. - target: F extends new (...args: any) => any ? F<F> : undefined
If the mocked function is a constructor, this field contains the class being constructed. Otherwise this will be
undefined.
interface MockFunctionContext<F extends Function>
The
MockFunctionContextclass is used to inspect or manipulate the behavior of mocks created via theMockTrackerAPIs.- readonly calls: MockFunctionCall<F, F extends (...args: any) => T ? T : F extends new (...args: any) => T ? T : unknown, F extends (...args: Y) => any ? Y : F extends new (...args: Y) => any ? Y : unknown[]>[]
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.
This function returns the number of times that this mock has been invoked. This function is more efficient than checking
ctx.calls.lengthbecausectx.callsis a getter that creates a copy of the internal call tracking array.@returnsThe number of times that this mock has been invoked.
- 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); });@param implementationThe function to be used as the mock's new implementation.
- implementation: F,onCall?: number): void;
This function is used to change the behavior of an existing mock for a single invocation. Once invocation
onCallhas occurred, the mock will revert to whatever behavior it would have used hadmockImplementationOnce()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); });@param implementationThe function to be used as the mock's implementation for the invocation number specified by
onCall.@param onCallThe invocation number that will use
implementation. If the specified invocation has already occurred then an exception is thrown. Resets the call history of the mock function.
Resets the implementation of the mock function to its original behavior. The mock can still be used after calling this function.
interface MockFunctionOptions
- times?: number
The number of times that the mock will use the behavior of
implementation. Once the mock function has been calledtimestimes, it will automatically restore the behavior oforiginal. This value must be an integer greater than zero.
interface MockMethodOptions
- getter?: boolean
If
true,object[methodName]is treated as a getter. This option cannot be used with thesetteroption. - setter?: boolean
If
true,object[methodName]is treated as a setter. This option cannot be used with thegetteroption. - times?: number
The number of times that the mock will use the behavior of
implementation. Once the mock function has been calledtimestimes, it will automatically restore the behavior oforiginal. This value must be an integer greater than zero.
interface MockModuleOptions
- cache?: boolean
If false, each call to
require()orimport()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. - exports?: object
Optional mocked exports. The
defaultproperty, if provided, is used as the mocked module's default export. All other own enumerable properties are used as named exports. This option cannot be used withdefaultExportornamedExports.- If the mock is a CommonJS or builtin module,
exports.defaultis used as the value ofmodule.exports. - If
exports.defaultis not provided for a CommonJS or builtin mock,module.exportsdefaults to an empty object. - If named exports are provided with a non-object default export, the mock throws an exception when used as a CommonJS or builtin module.
- If the mock is a CommonJS or builtin module,
interface MockTimers
Mocking timers is a technique commonly used in software testing to simulate and control the behavior of timers, such as
setIntervalandsetTimeout, without actually waiting for the specified time intervals.The MockTimers API also allows for mocking of the
Dateconstructor andsetImmediate/clearImmediatefunctions.The
MockTrackerprovides a top-leveltimersexport which is aMockTimersinstance.Calls ().
- ): 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
Datewill 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
Dateconstructor,setIntervaltimer and implicitly mocks theclearIntervalfunction. Only theDateconstructor fromglobalThis,setIntervalandclearIntervalfunctions fromnode:timers,node:timers/promises, andglobalThiswill 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, andclearTimeoutfunctions fromnode:timers,node:timers/promises, andglobalThiswill be mocked. TheDateconstructor fromglobalThiswill 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. This function restores the default behavior of all mocks that were previously created by this
MockTimersinstance and disassociates the mocks from theMockTrackerinstance.Note: After each test completes, this function is called on the test context's
MockTracker.import { mock } from 'node:test'; mock.timers.reset();Triggers all pending mocked timers immediately. If the
Dateobject is also mocked, it will also advance theDateobject 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.- milliseconds: number): void;
Sets the current Unix timestamp that will be used as reference for any mocked
Dateobjects.import assert from 'node:assert'; import { test } from 'node:test'; test('runAll functions following the given order', (context) => { const now = Date.now(); const setTime = 1000; // Date.now is not mocked assert.deepStrictEqual(Date.now(), now); context.mock.timers.enable({ apis: ['Date'] }); context.mock.timers.setTime(setTime); // Date.now is now 1000 assert.strictEqual(Date.now(), setTime); }); - tick(milliseconds: number): void;
Advances time for all mocked timers.
Note: This diverges from how
setTimeoutin Node.js behaves and accepts only positive numbers. In Node.js,setTimeoutwith negative numbers is only supported for web compatibility reasons.The following example mocks a
setTimeoutfunction and by using.tickadvances 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
.tickfunction can be called many timesimport 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
.tickwill also advance the time for anyDateobject created after the mock was enabled (ifDatewas 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); });
interface MockTimersOptions
interface MockTracker
The
MockTrackerclass is used to manage mocking functionality. The test runner module provides a top levelmockexport which is aMockTrackerinstance. Each test also provides its ownMockTrackerinstance via the test context'smockproperty.- original?: 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
timesoption 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); });@param originalAn optional function to create a mock on.
@param optionsOptional configuration options for the mock function.
@returnsThe mocked function. The mocked function contains a special
mockproperty, which is an instance of MockFunctionContext, and can be used for inspecting and changing the behavior of the mocked function.original?: F,implementation?: Implementation, - object: MockedObject,methodName: MethodName,
This function is syntax sugar for
MockTracker.methodwithoptions.getterset totrue.getter<MockedObject extends object, MethodName extends string | number | symbol, Implementation extends Function>(object: MockedObject,methodName: MethodName,implementation?: Implementation, - object: MockedObject,methodName: MethodName,
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); });@param objectThe object whose method is being mocked.
@param methodNameThe identifier of the method on
objectto mock. Ifobject[methodName]is not a function, an error is thrown.@param optionsOptional configuration options for the mock method.
@returnsThe mocked method. The mocked method contains a special
mockproperty, which is an instance of MockFunctionContext, and can be used for inspecting and changing the behavior of the mocked method.method<MockedObject extends object, MethodName extends string | number | symbol, Implementation extends Function>(object: MockedObject,methodName: MethodName,implementation: Implementation,object: MockedObject,methodName: keyof MockedObject,object: MockedObject,methodName: keyof MockedObject,implementation: Function, 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-mockscommand-line flag.Note: module customization hooks registered via the synchronous API effect resolution of the
specifierprovided tomock.module. Customization hooks registered via the asynchronous API are currently ignored (because the test runner's loader is synchronous, and node does not support multi-chain / cross-chain loading).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 'foo', which // does not exist in the original 'node:readline' module. const mock = t.mock.module('node:readline', { exports: { foo: () => 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); });@param specifierA string identifying the module to mock.
@param optionsOptional configuration options for the mock module.
- object: MockedObject,property: PropertyName,value?: MockedObject[PropertyName]
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); });@param objectThe object whose value is being mocked.
@param valueAn optional value used as the mock value for
object[propertyName]. Default: The original property value.@returnsA proxy to the mocked object. The mocked object contains a special
mockproperty, which is an instance of [MockPropertyContext][], and can be used for inspecting and changing the behavior of the mocked property. This function restores the default behavior of all mocks that were previously created by this
MockTrackerand disassociates the mocks from theMockTrackerinstance. Once disassociated, the mocks can still be used, but theMockTrackerinstance 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 globalMockTrackeris used extensively, calling this function manually is recommended.This function restores the default behavior of all mocks that were previously created by this
MockTracker. Unlikemock.reset(),mock.restoreAll()does not disassociate the mocks from theMockTrackerinstance.- object: MockedObject,methodName: MethodName,
This function is syntax sugar for
MockTracker.methodwithoptions.setterset totrue.setter<MockedObject extends object, MethodName extends string | number | symbol, Implementation extends Function>(object: MockedObject,methodName: MethodName,implementation?: Implementation,
interface RunOptions
- argv?: readonly string[]
An array of CLI flags to pass to each test file when spawning the subprocesses. This option has no effect when
isolationis'none'. - branchCoverage?: number
Require a minimum percent of covered branches. If code coverage does not reach the threshold specified, the process will exit with code
1. - concurrency?: number | boolean
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 runos.availableParallelism() - 1test files in parallel. Iffalse, it would only run one test file at a time. - coverageExcludeGlobs?: string | readonly string[]
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
coveragewas set totrue. If bothcoverageExcludeGlobsandcoverageIncludeGlobsare provided, files must meet both criteria to be included in the coverage report. - coverageIncludeGlobs?: string | readonly string[]
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
coveragewas set totrue. If bothcoverageExcludeGlobsandcoverageIncludeGlobsare provided, files must meet both criteria to be included in the coverage report. - cwd?: string
Specifies the current working directory to be used by the test runner. Serves as the base path for resolving files according to the test runner execution model.
- env?: ProcessEnv
Specify environment variables to be passed along to the test process. This option is not compatible with
isolation='none'. These variables will override those from the main process, and are not merged withprocess.env. - execArgv?: readonly string[]
An array of CLI flags to pass to the
nodeexecutable when spawning the subprocesses. This option has no effect whenisolationis'none'. - files?: readonly string[]
An array containing the list of files to run. If omitted, files are run according to the test runner execution model.
- forceExit?: boolean
Configures the test runner to exit the process once all known tests have finished executing even if the event loop would otherwise remain active.
- functionCoverage?: number
Require a minimum percent of covered functions. If code coverage does not reach the threshold specified, the process will exit with code
1. - globPatterns?: readonly string[]
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
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 theisolationoption is set to'none'as no child processes are spawned. - isolation?: 'process' | 'none'
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. - lineCoverage?: number
Require a minimum percent of covered lines. If code coverage does not reach the threshold specified, the process will exit with code
1. - randomize?: boolean
Randomize execution order for test files and queued tests. This option is not supported with
watch: true. - randomSeed?: number
Seed used when randomizing execution order. If this option is set, runs can replay the same randomized order deterministically, and setting this option also enables randomization. The value must be an integer between
0and4294967295. - rerunFailuresFilePath?: string
A file path where the test runner will store the state of the tests to allow rerunning only the failed tests on a next run.
- setup?: (reporter: TestsStream) => void | Promise<void>
A function that accepts the
TestsStreaminstance and can be used to setup listeners before any tests are run. - testNamePatterns?: string | RegExp | readonly string | RegExp[]
If provided, only run tests whose name matches the provided pattern. Strings are interpreted as JavaScript regular expressions.
- testSkipPatterns?: string | RegExp | readonly string | RegExp[]
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. - testTagFilters?: string | readonly string[]
A tag name, or an array of tag names, used to filter tests by their declared tags. Tests must contain every listed tag to run. Equivalent to passing
--experimental-test-tag-filteron the command line. See Test tags. - timeout?: number
The number of milliseconds after which the test execution will fail. If unspecified, subtests inherit this value from their parent.
interface SuiteContext
An instance of
SuiteContextis passed to each suite function in order to interact with the test runner. However, theSuiteContextconstructor is not exposed as part of the API.- readonly attempt: number
The attempt number of the suite. This value is zero-based, so the first attempt is
0, the second attempt is1, and so on. This property is useful in conjunction with the--test-rerun-failuresoption to determine the attempt number of the current run. - readonly filePath: undefined | string
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.
- message: string): void;
Output a diagnostic message. This is typically used for logging information about the current suite or its tests.
test.describe('my suite', (suite) => { suite.diagnostic('Suite diagnostic message'); });@param messageA diagnostic message to output.
interface TestContext
An instance of
TestContextis passed to each test function in order to interact with the test runner. However, theTestContextconstructor is not exposed as part of the API.- readonly assert: TestContextAssert
An object containing assertion methods bound to the test context. The top-level functions from the
node:assertmodule are exposed here for the purpose of creating test plans.Note: Some of the functions from
node:assertcontain type assertions. If these are called via the TestContextassertobject, 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. }); - readonly attempt: number
The attempt number of the test. This value is zero-based, so the first attempt is
0, the second attempt is1, and so on. This property is useful in conjunction with the--test-rerun-failuresoption to determine which attempt the test is currently running. - readonly filePath: undefined | string
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.
- readonly signal: AbortSignal
test('top level test', async (t) => { await fetch('some/uri', { signal: t.signal }); }); - readonly workerId: undefined | number
The unique identifier of the worker running the current test file. This value is derived from the
NODE_TEST_WORKER_IDenvironment 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 isundefinedwhen 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 }); - ): void;
This function is used to create a hook that runs after the current test finishes.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- ): void;
This function is used to create a hook running after each subtest of the current test.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- ): void;
This function is used to create a hook running before subtest of the current test.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- ): void;
This function is used to create a hook running before each subtest of the current test.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- 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'); });@param messageMessage to be reported.
- plan(count: number,): void;
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.assertmust be used instead ofassertdirectly.test('top level test', (t) => { t.plan(2); t.assert.ok('some relevant assertion here'); t.test('subtest', () => {}); });When working with asynchronous code, the
planfunction 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(); }); });When using the
waitoption, 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. });Note: If a
waittimeout is specified, it begins counting down only after the test function finishes executing. - shouldRunOnlyTests: boolean): void;
If
shouldRunOnlyTestsis truthy, the test context will only run tests that have theonlyoption set. Otherwise, all tests are run. If Node.js was not started with the--test-onlycommand-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 }), ]); });@param shouldRunOnlyTestsWhether or not to run
onlytests. - skip(message?: string): void;
This function causes the test's output to indicate the test as skipped. If
messageis provided, it is included in the output. Callingskip()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'); });@param messageOptional skip message.
- todo(message?: string): void;
This function adds a
TODOdirective to the test's output. Ifmessageis provided, it is included in the output. Callingtodo()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'); });@param messageOptional
TODOmessage. - condition: () => T,): Promise<Awaited<T>>;
This method polls a
conditionfunction until that function either returns successfully or the operation times out.@param conditionAn 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.
@param optionsAn optional configuration object for the polling operation.
@returnsFulfilled with the value returned by
condition.
interface TestContextAssert
- deepEqual: {(actual: unknown, expected: unknown, message?: Error | AssertMessageFunction) => void; (actual: unknown, expected: unknown, message: string, ...args: unknown[]) => void}
- deepStrictEqual: {(actual: unknown, expected: T, message?: Error | AssertMessageFunction) => asserts actual is T; (actual: unknown, expected: T, message: string, ...args: unknown[]) => asserts actual is T}
- doesNotMatch: {(value: string, regExp: RegExp, message?: Error | AssertMessageFunction) => void; (value: string, regExp: RegExp, message: string, ...args: unknown[]) => void}
- doesNotReject: {(block: Promise<unknown> | () => Promise<unknown>, message?: string | Error) => Promise<void>; (block: Promise<unknown> | () => Promise<unknown>, error: AssertPredicate, message?: string | Error) => Promise<void>}
- doesNotThrow: {(block: () => unknown, message?: string | Error) => void; (block: () => unknown, error: AssertPredicate, message?: string | Error) => void}
- equal: {(actual: unknown, expected: unknown, message?: Error | AssertMessageFunction) => void; (actual: unknown, expected: unknown, message: string, ...args: unknown[]) => void}
- match: {(value: string, regExp: RegExp, message?: Error | AssertMessageFunction) => void; (value: string, regExp: RegExp, message: string, ...args: unknown[]) => void}
- notDeepEqual: {(actual: unknown, expected: unknown, message?: Error | AssertMessageFunction) => void; (actual: unknown, expected: unknown, message: string, ...args: unknown[]) => void}
- notDeepStrictEqual: {(actual: unknown, expected: unknown, message?: Error | AssertMessageFunction) => void; (actual: unknown, expected: unknown, message: string, ...args: unknown[]) => void}
- notEqual: {(actual: unknown, expected: unknown, message?: Error | AssertMessageFunction) => void; (actual: unknown, expected: unknown, message: string, ...args: unknown[]) => void}
- notStrictEqual: {(actual: unknown, expected: unknown, message?: Error | AssertMessageFunction) => void; (actual: unknown, expected: unknown, message: string, ...args: unknown[]) => void}
- ok: {(value: unknown, message?: Error | AssertMessageFunction) => asserts value; (value: unknown, message: string, ...args: unknown[]) => asserts value}
- partialDeepStrictEqual: {(actual: unknown, expected: unknown, message?: Error | AssertMessageFunction) => void; (actual: unknown, expected: unknown, message: string, ...args: unknown[]) => void}
- rejects: {(block: Promise<unknown> | () => Promise<unknown>, message?: string | Error) => Promise<void>; (block: Promise<unknown> | () => Promise<unknown>, error: AssertPredicate, message?: string | Error) => Promise<void>}
- strictEqual: {(actual: unknown, expected: T, message?: Error | AssertMessageFunction) => asserts actual is T; (actual: unknown, expected: T, message: string, ...args: unknown[]) => asserts actual is T}
- throws: {(block: () => unknown, message?: string | Error) => void; (block: () => unknown, error: AssertPredicate, message?: string | Error) => void}
- value: any,path: string,): void;
This function serializes
valueand writes it to the file specified bypath.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.
@param valueA value to serialize to a string. If Node.js was started with the
--test-update-snapshotsflag, the serialized value is written topath. Otherwise, the serialized value is compared to the contents of the existing snapshot file.@param pathThe file where the serialized
valueis written.@param optionsOptional configuration options.
- value: any,): 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)] }); });@param valueA value to serialize to a string. If Node.js was started with the
--test-update-snapshotsflag, the serialized value is written to the snapshot file. Otherwise, the serialized value is compared to the corresponding value in the existing snapshot file.
interface TestContextPlanOptions
- wait?: number | boolean
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.
- If
interface TestContextWaitForOptions
interface TestOptions
- concurrency?: number | boolean
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
Infinitytests in parallel. If falsy, it would only run one test at a time. If unspecified, subtests inherit this value from their parent. - expectFailure?: string | boolean | AssertPredicate
If truthy, the test is expected to fail. If a non-empty string is provided, that string is displayed in the test results as the reason why the test is expected to fail. If a
RegExp,Function,Object, orErroris provided directly (without wrapping in{ match: … }), the test passes only if the thrown error matches, following the behavior ofassert.throws. To provide both a reason and validation, pass an object withlabel(string) andmatch(RegExp, Function, Object, or Error). - only?: boolean
If truthy, and the test context is configured to run
onlytests, then this test will be run. Otherwise, the test is skipped. - 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.
- skip?: string | boolean
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
A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent.
- todo?: string | boolean
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 isTODO.
interface TestsStream
A successful call to
run()will return a newTestsStreamobject, 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.
- readable: boolean
Is
trueif it is safe to call read, which means the stream has not been destroyed or emitted'error'or'end'. - readonly readableAborted: boolean
Returns whether the stream was destroyed or errored before emitting
'end'. - readonly readableEncoding: null | BufferEncoding
Getter for the property
encodingof a givenReadablestream. Theencodingproperty can be set using the setEncoding method. - readableFlowing: null | boolean
This property reflects the current state of a
Readablestream as described in the Three states section. - readonly readableHighWaterMark: number
Returns the value of
highWaterMarkpassed when creating thisReadable. - readonly readableLength: number
This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the
highWaterMark. Calls
readable.destroy()with anAbortErrorand returns a promise that fulfills when the stream is finished.- @returns
AsyncIteratorto fully consume the stream. - event: string | symbol,...args: any[]): void;
The
Symbol.for('nodejs.rejection')method is called in case a promise rejection happens when emitting an event andcaptureRejectionsis enabled on the emitter. It is possible to useevents.captureRejectionSymbolin place ofSymbol.for('nodejs.rejection').import { EventEmitter, captureRejectionSymbol } from 'node:events'; class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); } [captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); } destroy(err) { // Tear the resource down here. } } When the
--experimental-stream-iterflag is enabled,Readablestreams implement theStream.toAsyncStreamableprotocol, enabling efficient consumption by thestream/iterAPI.This provides a batched async iterator that drains the stream's internal buffer into
Uint8Array[]batches, amortizing the per-chunk Promise overhead of the standardSymbol.asyncIteratorpath. For byte-mode streams, chunks are yielded directly asBufferinstances (which areUint8Arraysubclasses). For object-mode or encoded streams, each chunk is normalized toUint8Arraybefore batching.The returned iterator is tagged as a validated source, so
from()passes it through without additional normalization.import { Readable } from 'node:stream'; import { text, from } from 'node:stream/iter'; const readable = new Readable({ read() { this.push('hello'); this.push(null); }, }); // Readable is automatically consumed via toAsyncStreamable console.log(await text(from(readable))); // 'hello'Without the
--experimental-stream-iterflag, calling this method throwsERR_STREAM_ITER_MISSING_FLAG.- eventName: E,): this;
Alias for
emitter.on(eventName, listener). import { Readable } from 'node:stream'; async function* splitToWords(source) { for await (const chunk of source) { const words = String(chunk).split(' '); for (const word of words) { yield word; } } } const wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords); const words = await wordsStream.toArray(); console.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream']readable.compose(s)is equivalent tostream.compose(readable, s).This method also allows for an
AbortSignalto be provided, which will destroy the composed stream when aborted.See
stream.compose(...streams)for more information.@returnsa stream composed with the stream
stream.- ): this;
Destroy the stream. Optionally emit an
'error'event, and emit a'close'event (unlessemitCloseis set tofalse). After this call, the readable stream will release any internal resources and subsequent calls topush()will be ignored.Once
destroy()has been called any further calls will be a no-op and no further errors except from_destroy()may be emitted as'error'.Implementors should not override this method, but instead implement
readable._destroy().@param errorError which will be passed as payload in
'error'event - eventName: E,): boolean;
Synchronously calls each of the listeners registered for the event named
eventName, in the order they were registered, passing the supplied arguments to each.Returns
trueif the event had listeners,falseotherwise.import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener Returns an array listing the events for which the emitter has registered listeners.
import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ]- ): Promise<boolean>;
This method is similar to
Array.prototype.everyand calls fn on each chunk in the stream to check if all awaited return values are truthy value for fn. Once an fn call on a chunkawaited return value is falsy, the stream is destroyed and the promise is fulfilled withfalse. If all of the fn calls on the chunks return a truthy value, the promise is fulfilled withtrue.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to
trueif fn returned a truthy value for every one of the chunks. This method allows filtering the stream. For each chunk in the stream the fn function will be called and if it returns a truthy value, the chunk will be passed to the result stream. If the fn function returns a promise - that promise will be
awaited.@param fna function to filter chunks from the stream. Async or not.
@returnsa stream filtered with the predicate fn.
- ): Promise<undefined | T>;
This method is similar to
Array.prototype.findand calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled withundefined.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to the first chunk for which fn evaluated with a truthy value, or
undefinedif no element was found.find(): Promise<any>;This method is similar to
Array.prototype.findand calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled withundefined.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to the first chunk for which fn evaluated with a truthy value, or
undefinedif no element was found. This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.
It is possible to return a stream or another iterable or async iterable from fn and the result streams will be merged (flattened) into the returned stream.
@param fna function to map over every chunk in the stream. May be async. May be a stream or generator.
@returnsa stream flat-mapped with the function fn.
- ): Promise<void>;
This method allows iterating a stream. For each chunk in the stream the fn function will be called. If the fn function returns a promise - that promise will be
awaited.This method is different from
for await...ofloops in that it can optionally process chunks concurrently. In addition, aforEachiteration can only be stopped by having passed asignaloption and aborting the related AbortController whilefor await...ofcan be stopped withbreakorreturn. In either case the stream will be destroyed.This method is different from listening to the
'data'event in that it uses thereadableevent in the underlying machinary and can limit the number of concurrent fn calls.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise for when the stream has finished.
Returns the current max listener value for the
EventEmitterwhich is either set byemitter.setMaxListeners(n)or defaults toevents.defaultMaxListeners.The
readable.isPaused()method returns the current operating state of theReadable. This is used primarily by the mechanism that underlies thereadable.pipe()method. In most typical cases, there will be no reason to use this method directly.const readable = new stream.Readable(); readable.isPaused(); // === false readable.pause(); readable.isPaused(); // === true readable.resume(); readable.isPaused(); // === false- ): AsyncIterator<any>;
The iterator created by this method gives users the option to cancel the destruction of the stream if the
for await...ofloop is exited byreturn,break, orthrow, or if the iterator should destroy the stream if the stream emitted an error during iteration. - eventName: E,): number;
Returns the number of listeners listening for the event named
eventName. Iflisteneris provided, it will return how many times the listener is found in the list of the listeners of the event.@param eventNameThe name of the event being listened for
@param listenerThe event handler function
- eventName: E
Returns a copy of the array of listeners for the event named
eventName.server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] - map(
This method allows mapping over the stream. The fn function will be called for every chunk in the stream. If the fn function returns a promise - that promise will be
awaited before being passed to the result stream.@param fna function to map over every chunk in the stream. Async or not.
@returnsa stream mapped with the function fn.
- eventName: E,): this;
Alias for
emitter.removeListener(). - eventName: E,): this;
Adds the
listenerfunction to the end of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing added, and called, multiple times.server.on('connection', (stream) => { console.log('someone connected!'); });Returns a reference to the
EventEmitter, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependListener()method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a@param eventNameThe name of the event.
@param listenerThe callback function
- eventName: E,): this;
Adds a one-time
listenerfunction for the event namedeventName. The next timeeventNameis triggered, this listener is removed and then invoked.server.once('connection', (stream) => { console.log('Ah, we have our first user!'); });Returns a reference to the
EventEmitter, so that calls can be chained.By default, event listeners are invoked in the order they are added. The
emitter.prependOnceListener()method can be used as an alternative to add the event listener to the beginning of the listeners array.import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a@param eventNameThe name of the event.
@param listenerThe callback function
The
readable.pause()method will cause a stream in flowing mode to stop emitting'data'events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); readable.pause(); console.log('There will be no additional data for 1 second.'); setTimeout(() => { console.log('Now data will start flowing again.'); readable.resume(); }, 1000); });The
readable.pause()method has no effect if there is a'readable'event listener.- eventName: E,): this;
Adds the
listenerfunction to the beginning of the listeners array for the event namedeventName. No checks are made to see if thelistenerhas already been added. Multiple calls passing the same combination ofeventNameandlistenerwill result in thelistenerbeing added, and called, multiple times.server.prependListener('connection', (stream) => { console.log('someone connected!'); });Returns a reference to the
EventEmitter, so that calls can be chained.@param eventNameThe name of the event.
@param listenerThe callback function
- eventName: E,): this;
Adds a one-time
listenerfunction for the event namedeventNameto the beginning of the listeners array. The next timeeventNameis triggered, this listener is removed, and then invoked.server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); });Returns a reference to the
EventEmitter, so that calls can be chained.@param eventNameThe name of the event.
@param listenerThe callback function
- eventName: E
Returns a copy of the array of listeners for the event named
eventName, including any wrappers (such as those created by.once()).import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); - read(size?: number): any;
The
readable.read()method reads data out of the internal buffer and returns it. If no data is available to be read,nullis returned. By default, the data is returned as aBufferobject unless an encoding has been specified using thereadable.setEncoding()method or the stream is operating in object mode.The optional
sizeargument specifies a specific number of bytes to read. Ifsizebytes are not available to be read,nullwill be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.If the
sizeargument is not specified, all of the data contained in the internal buffer will be returned.The
sizeargument must be less than or equal to 1 GiB.The
readable.read()method should only be called onReadablestreams operating in paused mode. In flowing mode,readable.read()is called automatically until the internal buffer is fully drained.const readable = getReadableStreamSomehow(); // 'readable' may be triggered multiple times as data is buffered in readable.on('readable', () => { let chunk; console.log('Stream is readable (new data received in buffer)'); // Use a loop to make sure we read all currently available data while (null !== (chunk = readable.read())) { console.log(`Read ${chunk.length} bytes of data...`); } }); // 'end' will be triggered once when there is no more data available readable.on('end', () => { console.log('Reached end of stream.'); });Each call to
readable.read()returns a chunk of data, ornull. The chunks are not concatenated. Awhileloop is necessary to consume all data currently in the buffer. When reading a large file.read()may returnnull, having consumed all buffered content so far, but there is still more data to come not yet buffered. In this case a new'readable'event will be emitted when there is more data in the buffer. Finally the'end'event will be emitted when there is no more data to come.Therefore to read a file's whole contents from a
readable, it is necessary to collect chunks across multiple'readable'events:const chunks = []; readable.on('readable', () => { let chunk; while (null !== (chunk = readable.read())) { chunks.push(chunk); } }); readable.on('end', () => { const content = chunks.join(''); });A
Readablestream in object mode will always return a single item from a call toreadable.read(size), regardless of the value of thesizeargument.If the
readable.read()method returns a chunk of data, a'data'event will also be emitted.Calling read after the
'end'event has been emitted will returnnull. No runtime error will be raised.@param sizeOptional argument to specify how much data to read.
- ): Promise<T>;
This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.
If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a
TypeErrorwith theERR_INVALID_ARGScode property.The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to
readable.mapmethod.@param fna reducer function to call over every chunk in the stream. Async or not.
@returnsa promise for the final value of the reduction.
initial: T,): Promise<T>;This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.
If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a
TypeErrorwith theERR_INVALID_ARGScode property.The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to
readable.mapmethod.@param fna reducer function to call over every chunk in the stream. Async or not.
@param initialthe initial value to use in the reduction.
@returnsa promise for the final value of the reduction.
- eventName?: E): this;
Removes all listeners, or those of the specified
eventName.It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitterinstance was created by some other component or module (e.g. sockets or file streams).Returns a reference to the
EventEmitter, so that calls can be chained. - eventName: E,): this;
Removes the specified
listenerfrom the listener array for the event namedeventName.const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback);removeListener()will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specifiedeventName, thenremoveListener()must be called multiple times to remove each instance.Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any
removeListener()orremoveAllListeners()calls after emitting and before the last listener finishes execution will not remove them fromemit()in progress. Subsequent events behave as expected.import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // ABecause listeners are managed using an internal array, calling this will change the position indexes of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the
emitter.listeners()method will need to be recreated.When a single function has been added as a handler multiple times for a single event (as in the example below),
removeListener()will remove the most recently added instance. In the example theonce('ping')listener is removed:import { EventEmitter } from 'node:events'; const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping');Returns a reference to the
EventEmitter, so that calls can be chained. The
readable.resume()method causes an explicitly pausedReadablestream to resume emitting'data'events, switching the stream into flowing mode.The
readable.resume()method can be used to fully consume the data from a stream without actually processing any of that data:getReadableStreamSomehow() .resume() .on('end', () => { console.log('Reached the end, but did not read anything.'); });The
readable.resume()method has no effect if there is a'readable'event listener.- encoding: BufferEncoding): this;
The
readable.setEncoding()method sets the character encoding for data read from theReadablestream.By default, no encoding is assigned and stream data will be returned as
Bufferobjects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than asBufferobjects. For instance, callingreadable.setEncoding('utf8')will cause the output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex')will cause the data to be encoded in hexadecimal string format.The
Readablestream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream asBufferobjects.const readable = getReadableStreamSomehow(); readable.setEncoding('utf8'); readable.on('data', (chunk) => { assert.equal(typeof chunk, 'string'); console.log('Got %d characters of string data:', chunk.length); });@param encodingThe encoding to use.
- n: number): this;
By default
EventEmitters will print a warning if more than10listeners are added for a particular event. This is a useful default that helps finding memory leaks. Theemitter.setMaxListeners()method allows the limit to be modified for this specificEventEmitterinstance. The value can be set toInfinity(or0) to indicate an unlimited number of listeners.Returns a reference to the
EventEmitter, so that calls can be chained. - some(): Promise<boolean>;
This method is similar to
Array.prototype.someand calls fn on each chunk in the stream until the awaited return value istrue(or any truthy value). Once an fn call on a chunkawaited return value is truthy, the stream is destroyed and the promise is fulfilled withtrue. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled withfalse.@param fna function to call on each chunk of the stream. Async or not.
@returnsa promise evaluating to
trueif fn returned a truthy value for at least one of the chunks. - ): Promise<any[]>;
This method allows easily obtaining the contents of a stream.
As this method reads the entire stream into memory, it negates the benefits of streams. It's intended for interoperability and convenience, not as the primary way to consume streams.
@returnsa promise containing an array with the contents of the stream.
- destination?: WritableStream): this;
The
readable.unpipe()method detaches aWritablestream previously attached using the pipe method.If the
destinationis not specified, then all pipes are detached.If the
destinationis specified, but no pipe is set up for it, then the method does nothing.import fs from 'node:fs'; const readable = getReadableStreamSomehow(); const writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt', // but only for the first second. readable.pipe(writable); setTimeout(() => { console.log('Stop writing to file.txt.'); readable.unpipe(writable); console.log('Manually close the file stream.'); writable.end(); }, 1000);@param destinationOptional specific stream to unpipe
- chunk: any,encoding?: BufferEncoding): void;
Passing
chunkasnullsignals the end of the stream (EOF) and behaves the same asreadable.push(null), after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed.The
readable.unshift()method pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.The
stream.unshift(chunk)method cannot be called after the'end'event has been emitted or a runtime error will be thrown.Developers using
stream.unshift()often should consider switching to use of aTransformstream instead. See theAPI for stream implementerssection for more information.// Pull off a header delimited by \n\n. // Use unshift() if we get too much. // Call the callback with (error, header, stream). import { StringDecoder } from 'node:string_decoder'; function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); const decoder = new StringDecoder('utf8'); let header = ''; function onReadable() { let chunk; while (null !== (chunk = stream.read())) { const str = decoder.write(chunk); if (str.includes('\n\n')) { // Found the header boundary. const split = str.split(/\n\n/); header += split.shift(); const remaining = split.join('\n\n'); const buf = Buffer.from(remaining, 'utf8'); stream.removeListener('error', callback); // Remove the 'readable' listener before unshifting. stream.removeListener('readable', onReadable); if (buf.length) stream.unshift(buf); // Now the body of the message can be read from the stream. callback(null, header, stream); return; } // Still reading the header. header += str; } } }Unlike push,
stream.unshift(chunk)will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results ifreadable.unshift()is called during a read (i.e. from within a _read implementation on a custom stream). Following the call toreadable.unshift()with an immediate push will reset the reading state appropriately, however it is best to simply avoid callingreadable.unshift()while in the process of performing a read.@param chunkChunk of data to unshift onto the read queue. For streams not operating in object mode,
chunkmust be a {string}, {Buffer}, {TypedArray}, {DataView} ornull. For object mode streams,chunkmay be any JavaScript value.@param encodingEncoding of string chunks. Must be a valid
Bufferencoding, such as'utf8'or'ascii'. - wrap(stream: ReadableStream): this;
Prior to Node.js 0.10, streams did not implement the entire
node:streammodule API as it is currently defined. (SeeCompatibilityfor more information.)When using an older Node.js library that emits
'data'events and has a pause method that is advisory only, thereadable.wrap()method can be used to create aReadablestream that uses the old stream as its data source.It will rarely be necessary to use
readable.wrap()but the method has been provided as a convenience for interacting with older Node.js applications and libraries.import { OldReader } from './old-api-module.js'; import { Readable } from 'node:stream'; const oreader = new OldReader(); const myReader = new Readable().wrap(oreader); myReader.on('readable', () => { myReader.read(); // etc. });@param streamAn "old style" readable stream
interface TestsStreamEventMap
- type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any
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.
- type Mock<F extends Function> = F & { mock: MockFunctionContext<F> }
- type SuiteFn = (s: SuiteContext) => void | Promise<void>
The type of a suite test function. The argument to this function is a SuiteContext object.
- type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any
The hook function. The first argument is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument. - type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise<void>
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.
- ): void;
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 }); });@param fnThe hook function. If the hook uses callbacks, the callback function is passed as the second argument.
@param optionsConfiguration options for the hook.
- ): void;
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 }); });@param fnThe hook function. If the hook uses callbacks, the callback function is passed as the second argument.
@param optionsConfiguration options for the hook.
- ): void;
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 assertion here }); });@param fnThe hook function. If the hook uses callbacks, the callback function is passed as the second argument.
@param optionsConfiguration options for the hook.
- ): void;
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 }); });@param fnThe hook function. If the hook uses callbacks, the callback function is passed as the second argument.
@param optionsConfiguration options for the hook.
Returns the TestContext or SuiteContext object associated with the currently executing test or suite, or
undefinedif called outside of a test or suite. This function can be used to access context information from within the test or suite function or any async operations within them.import { getTestContext } from 'node:test'; test('example test', async () => { const ctx = getTestContext(); console.log(`Running test: ${ctx.name}`); }); describe('example suite', () => { const ctx = getTestContext(); console.log(`Running suite: ${ctx.name}`); });When called from a test, returns a
TestContext. When called from a suite, returns aSuiteContext.If called from outside a test or suite (e.g., at the top level of a module or in a setTimeout callback after execution has completed), this function returns
undefined.When called from within a hook (before, beforeEach, after, afterEach), this function returns the context of the test or suite that the hook is associated with.
- name?: string,): Promise<void>;
Shorthand for marking a test as
only. This is the same as calling test withoptions.onlyset totrue.): Promise<void>;Shorthand for marking a test as
only. This is the same as calling test withoptions.onlyset totrue. Note:
shardis used to horizontally parallelize test running across machines or processes, ideal for large-scale executions across varied environments. It's incompatible withwatchmode, 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);@param optionsConfiguration options for running tests.
- name?: string,): Promise<void>;
Shorthand for skipping a test. This is the same as calling test with
options.skipset totrue.): Promise<void>;Shorthand for skipping a test. This is the same as calling test with
options.skipset totrue. - name?: string,): Promise<void>;
The
suite()function is imported from thenode:testmodule.@param nameThe name of the suite, which is displayed when reporting test results. Defaults to the
nameproperty offn, or'<anonymous>'iffndoes not have a name.@param optionsConfiguration options for the suite. This supports the same options as test.
@param fnThe suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
@returnsImmediately fulfilled with
undefined.name?: string,): Promise<void>;The
suite()function is imported from thenode:testmodule.@param nameThe name of the suite, which is displayed when reporting test results. Defaults to the
nameproperty offn, or'<anonymous>'iffndoes not have a name.@param fnThe suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
@returnsImmediately fulfilled with
undefined.): Promise<void>;The
suite()function is imported from thenode:testmodule.@param optionsConfiguration options for the suite. This supports the same options as test.
@param fnThe suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
@returnsImmediately fulfilled with
undefined.): Promise<void>;The
suite()function is imported from thenode:testmodule.@param fnThe suite function declaring nested tests and suites. The first argument to this function is a SuiteContext object.
@returnsImmediately fulfilled with
undefined.name?: string,): Promise<void>;This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
name?: string,): Promise<void>;This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
): Promise<void>;This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
): Promise<void>;This flips the pass/fail reporting for a specific test or suite: a flagged test case must throw in order to pass, and a flagged test case that does not throw fails.
name?: string,): Promise<void>;Shorthand for marking a suite as
only. This is the same as calling suite withoptions.onlyset totrue.): Promise<void>;Shorthand for marking a suite as
only. This is the same as calling suite withoptions.onlyset totrue.name?: string,): Promise<void>;Shorthand for skipping a suite. This is the same as calling suite with
options.skipset totrue.): Promise<void>;Shorthand for skipping a suite. This is the same as calling suite with
options.skipset totrue.name?: string,): Promise<void>;Shorthand for marking a suite as
TODO. This is the same as calling suite withoptions.todoset totrue.): Promise<void>;Shorthand for marking a suite as
TODO. This is the same as calling suite withoptions.todoset totrue. - name?: string,): Promise<void>;
Shorthand for marking a test as
TODO. This is the same as calling test withoptions.todoset totrue.): Promise<void>;Shorthand for marking a test as
TODO. This is the same as calling test withoptions.todoset totrue.