is provided directly (without wrapping in `{ match: … }`), the test passes only if the thrown error matches, following the behavior of `assert.throws`. To provide both a reason and validation, pass an object with `label` (string) and `match` (RegExp, Function, Object, or Error)."
},
{
"textRaw": "`only` {boolean} If truthy, and the test context is configured to run `only` tests, then this test will be run. Otherwise, the test is skipped. **Default:** `false`.",
"name": "only",
"type": "boolean",
"default": "`false`",
"desc": "If truthy, and the test context is configured to run `only` tests, then this test will be run. Otherwise, the test is skipped."
},
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress test.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress test."
},
{
"textRaw": "`skip` {boolean|string} If truthy, the test is skipped. If a string is provided, that string is displayed in the test results as the reason for skipping the test. **Default:** `false`.",
"name": "skip",
"type": "boolean|string",
"default": "`false`",
"desc": "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."
},
{
"textRaw": "`todo` {boolean|string} If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in the test results as the reason why the test is `TODO`. **Default:** `false`.",
"name": "todo",
"type": "boolean|string",
"default": "`false`",
"desc": "If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in the test results as the reason why the test is `TODO`."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent."
},
{
"textRaw": "`plan` {number} The number of assertions and subtests expected to be run in the test. If the number of assertions run in the test does not match the number specified in the plan, the test will fail. **Default:** `undefined`.",
"name": "plan",
"type": "number",
"default": "`undefined`",
"desc": "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."
}
],
"optional": true
},
{
"textRaw": "`fn` {Function|AsyncFunction} The function under test. The first argument to this function is a `TestContext` object. If the test uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "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.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite.",
"name": "return",
"type": "Promise",
"desc": "Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite."
}
}
],
"desc": "The test() function is the value imported from the test module. Each\ninvocation of this function results in reporting the test to the <TestsStream>.
\nThe TestContext object passed to the fn argument can be used to perform\nactions related to the current test. Examples include skipping the test, adding\nadditional diagnostic information, or creating subtests.
\ntest() returns a Promise that fulfills once the test completes.\nif test() is called within a suite, it fulfills immediately.\nThe return value can usually be discarded for top level tests.\nHowever, the return value from subtests should be used to prevent the parent\ntest from finishing first and cancelling the subtest\nas shown in the following example.
\ntest('top level test', async (t) => {\n // The setTimeout() in the following subtest would cause it to outlive its\n // parent test if 'await' is removed on the next line. Once the parent test\n // completes, it will cancel any outstanding subtests.\n await t.test('longer running subtest', async (t) => {\n return new Promise((resolve, reject) => {\n setTimeout(resolve, 1000);\n });\n });\n});\n
\nThe timeout option can be used to fail the test if it takes longer than\ntimeout milliseconds to complete. However, it is not a reliable mechanism for\ncanceling tests because a running test might block the application thread and\nthus prevent the scheduled cancellation.
"
},
{
"textRaw": "`test.skip([name][, options][, fn])`",
"name": "skip",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for skipping a test,\nsame as test([name], { skip: true }[, fn]).
"
},
{
"textRaw": "`test.todo([name][, options][, fn])`",
"name": "todo",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for marking a test as TODO,\nsame as test([name], { todo: true }[, fn]).
"
},
{
"textRaw": "`test.only([name][, options][, fn])`",
"name": "only",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for marking a test as only,\nsame as test([name], { only: true }[, fn]).
"
},
{
"textRaw": "`describe([name][, options][, fn])`",
"name": "describe",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Alias for suite().
\nThe describe() function is imported from the node:test module.
"
},
{
"textRaw": "`describe.skip([name][, options][, fn])`",
"name": "skip",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for skipping a suite. This is the same as\ndescribe([name], { skip: true }[, fn]).
"
},
{
"textRaw": "`describe.todo([name][, options][, fn])`",
"name": "todo",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for marking a suite as TODO. This is the same as\ndescribe([name], { todo: true }[, fn]).
"
},
{
"textRaw": "`describe.only([name][, options][, fn])`",
"name": "only",
"type": "method",
"meta": {
"added": [
"v19.8.0",
"v18.15.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for marking a suite as only. This is the same as\ndescribe([name], { only: true }[, fn]).
"
},
{
"textRaw": "`it([name][, options][, fn])`",
"name": "it",
"type": "method",
"meta": {
"added": [
"v18.6.0",
"v16.17.0"
],
"changes": [
{
"version": [
"v19.8.0",
"v18.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/46889",
"description": "Calling `it()` is now equivalent to calling `test()`."
}
]
},
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Alias for test().
\nThe it() function is imported from the node:test module.
"
},
{
"textRaw": "`it.skip([name][, options][, fn])`",
"name": "skip",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for skipping a test,\nsame as it([name], { skip: true }[, fn]).
"
},
{
"textRaw": "`it.todo([name][, options][, fn])`",
"name": "todo",
"type": "method",
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for marking a test as TODO,\nsame as it([name], { todo: true }[, fn]).
"
},
{
"textRaw": "`it.only([name][, options][, fn])`",
"name": "only",
"type": "method",
"meta": {
"added": [
"v19.8.0",
"v18.15.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"name": "name",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "fn",
"optional": true
}
]
}
],
"desc": "Shorthand for marking a test as only,\nsame as it([name], { only: true }[, fn]).
"
},
{
"textRaw": "`before([fn][, options])`",
"name": "before",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function creates a hook that runs before executing a suite.
\ndescribe('tests', async () => {\n before(() => console.log('about to run some test'));\n it('is a subtest', () => {\n // Some relevant assertions here\n });\n});\n
"
},
{
"textRaw": "`after([fn][, options])`",
"name": "after",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function creates a hook that runs after executing a suite.
\ndescribe('tests', async () => {\n after(() => console.log('finished running tests'));\n it('is a subtest', () => {\n // Some relevant assertion here\n });\n});\n
\nNote: The after hook is guaranteed to run,\neven if tests within the suite fail.
"
},
{
"textRaw": "`beforeEach([fn][, options])`",
"name": "beforeEach",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function creates a hook that runs before each test in the current suite.
\ndescribe('tests', async () => {\n beforeEach(() => console.log('about to run a test'));\n it('is a subtest', () => {\n // Some relevant assertion here\n });\n});\n
"
},
{
"textRaw": "`afterEach([fn][, options])`",
"name": "afterEach",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function creates a hook that runs after each test in the current suite.\nThe afterEach() hook is run even if the test fails.
\ndescribe('tests', async () => {\n afterEach(() => console.log('finished running a test'));\n it('is a subtest', () => {\n // Some relevant assertion here\n });\n});\n
"
}
],
"classes": [
{
"textRaw": "Class: `MockFunctionContext`",
"name": "MockFunctionContext",
"type": "class",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"desc": "The MockFunctionContext class is used to inspect or manipulate the behavior of\nmocks created via the MockTracker APIs.
",
"properties": [
{
"textRaw": "Type: {Array}",
"name": "calls",
"type": "Array",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"desc": "A getter that returns a copy of the internal array used to track calls to the\nmock. Each entry in the array is an object with the following properties.
\n\narguments <Array> An array of the arguments passed to the mock function. \nerror <any> If the mocked function threw then this property contains the\nthrown value. Default: undefined. \nresult <any> The value returned by the mocked function. \nstack <Error> An Error object whose stack can be used to determine the\ncallsite of the mocked function invocation. \ntarget <Function> | <undefined> If the mocked function is a constructor, this\nfield contains the class being constructed. Otherwise this will be undefined. \nthis <any> The mocked function's this value. \n
"
}
],
"methods": [
{
"textRaw": "`ctx.callCount()`",
"name": "callCount",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {integer} The number of times that this mock has been invoked.",
"name": "return",
"type": "integer",
"desc": "The number of times that this mock has been invoked."
}
}
],
"desc": "This function returns the number of times that this mock has been invoked. This\nfunction is more efficient than checking ctx.calls.length because ctx.calls\nis a getter that creates a copy of the internal call tracking array.
"
},
{
"textRaw": "`ctx.mockImplementation(implementation)`",
"name": "mockImplementation",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`implementation` {Function|AsyncFunction} The function to be used as the mock's new implementation.",
"name": "implementation",
"type": "Function|AsyncFunction",
"desc": "The function to be used as the mock's new implementation."
}
]
}
],
"desc": "This function is used to change the behavior of an existing mock.
\nThe following example creates a mock function using t.mock.fn(), calls the\nmock function, and then changes the mock implementation to a different function.
\ntest('changes a mock behavior', (t) => {\n let cnt = 0;\n\n function addOne() {\n cnt++;\n return cnt;\n }\n\n function addTwo() {\n cnt += 2;\n return cnt;\n }\n\n const fn = t.mock.fn(addOne);\n\n assert.strictEqual(fn(), 1);\n fn.mock.mockImplementation(addTwo);\n assert.strictEqual(fn(), 3);\n assert.strictEqual(fn(), 5);\n});\n
"
},
{
"textRaw": "`ctx.mockImplementationOnce(implementation[, onCall])`",
"name": "mockImplementationOnce",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`implementation` {Function|AsyncFunction} The function to be used as the mock's implementation for the invocation number specified by `onCall`.",
"name": "implementation",
"type": "Function|AsyncFunction",
"desc": "The function to be used as the mock's implementation for the invocation number specified by `onCall`."
},
{
"textRaw": "`onCall` {integer} The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. **Default:** The number of the next invocation.",
"name": "onCall",
"type": "integer",
"default": "The number of the next invocation",
"desc": "The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown.",
"optional": true
}
]
}
],
"desc": "This function is used to change the behavior of an existing mock for a single\ninvocation. Once invocation onCall has occurred, the mock will revert to\nwhatever behavior it would have used had mockImplementationOnce() not been\ncalled.
\nThe following example creates a mock function using t.mock.fn(), calls the\nmock function, changes the mock implementation to a different function for the\nnext invocation, and then resumes its previous behavior.
\ntest('changes a mock behavior once', (t) => {\n let cnt = 0;\n\n function addOne() {\n cnt++;\n return cnt;\n }\n\n function addTwo() {\n cnt += 2;\n return cnt;\n }\n\n const fn = t.mock.fn(addOne);\n\n assert.strictEqual(fn(), 1);\n fn.mock.mockImplementationOnce(addTwo);\n assert.strictEqual(fn(), 3);\n assert.strictEqual(fn(), 4);\n});\n
"
},
{
"textRaw": "`ctx.resetCalls()`",
"name": "resetCalls",
"type": "method",
"meta": {
"added": [
"v19.3.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Resets the call history of the mock function.
"
},
{
"textRaw": "`ctx.restore()`",
"name": "restore",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Resets the implementation of the mock function to its original behavior. The\nmock can still be used after calling this function.
"
}
]
},
{
"textRaw": "Class: `MockModuleContext`",
"name": "MockModuleContext",
"type": "class",
"meta": {
"added": [
"v22.3.0",
"v20.18.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Early development",
"desc": "The MockModuleContext class is used to manipulate the behavior of module mocks\ncreated via the MockTracker APIs.
",
"methods": [
{
"textRaw": "`ctx.restore()`",
"name": "restore",
"type": "method",
"meta": {
"added": [
"v22.3.0",
"v20.18.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Resets the implementation of the mock module.
"
}
]
},
{
"textRaw": "Class: `MockPropertyContext`",
"name": "MockPropertyContext",
"type": "class",
"meta": {
"added": [
"v24.3.0",
"v22.20.0"
],
"changes": []
},
"desc": "The MockPropertyContext class is used to inspect or manipulate the behavior\nof property mocks created via the MockTracker APIs.
",
"properties": [
{
"textRaw": "Type: {Array}",
"name": "accesses",
"type": "Array",
"desc": "A getter that returns a copy of the internal array used to track accesses (get/set) to\nthe mocked property. Each entry in the array is an object with the following properties:
\n\ntype <string> Either 'get' or 'set', indicating the type of access. \nvalue <any> The value that was read (for 'get') or written (for 'set'). \nstack <Error> An Error object whose stack can be used to determine the\ncallsite of the mocked function invocation. \n
"
}
],
"methods": [
{
"textRaw": "`ctx.accessCount()`",
"name": "accessCount",
"type": "method",
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {integer} The number of times that the property was accessed (read or written).",
"name": "return",
"type": "integer",
"desc": "The number of times that the property was accessed (read or written)."
}
}
],
"desc": "This function returns the number of times that the property was accessed.\nThis function is more efficient than checking ctx.accesses.length because\nctx.accesses is a getter that creates a copy of the internal access tracking array.
"
},
{
"textRaw": "`ctx.mockImplementation(value)`",
"name": "mockImplementation",
"type": "method",
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} The new value to be set as the mocked property value.",
"name": "value",
"type": "any",
"desc": "The new value to be set as the mocked property value."
}
]
}
],
"desc": "This function is used to change the value returned by the mocked property getter.
"
},
{
"textRaw": "`ctx.mockImplementationOnce(value[, onAccess])`",
"name": "mockImplementationOnce",
"type": "method",
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} The value to be used as the mock's implementation for the invocation number specified by `onAccess`.",
"name": "value",
"type": "any",
"desc": "The value to be used as the mock's implementation for the invocation number specified by `onAccess`."
},
{
"textRaw": "`onAccess` {integer} The invocation number that will use `value`. If the specified invocation has already occurred then an exception is thrown. **Default:** The number of the next invocation.",
"name": "onAccess",
"type": "integer",
"default": "The number of the next invocation",
"desc": "The invocation number that will use `value`. If the specified invocation has already occurred then an exception is thrown.",
"optional": true
}
]
}
],
"desc": "This function is used to change the behavior of an existing mock for a single\ninvocation. Once invocation onAccess has occurred, the mock will revert to\nwhatever behavior it would have used had mockImplementationOnce() not been\ncalled.
\nThe following example creates a mock function using t.mock.property(), calls the\nmock property, changes the mock implementation to a different value for the\nnext invocation, and then resumes its previous behavior.
\ntest('changes a mock behavior once', (t) => {\n const obj = { foo: 1 };\n\n const prop = t.mock.property(obj, 'foo', 5);\n\n assert.strictEqual(obj.foo, 5);\n prop.mock.mockImplementationOnce(25);\n assert.strictEqual(obj.foo, 25);\n assert.strictEqual(obj.foo, 5);\n});\n
",
"modules": [
{
"textRaw": "Caveat",
"name": "caveat",
"type": "module",
"desc": "For consistency with the rest of the mocking API, this function treats both property gets and sets\nas accesses. If a property set occurs at the same access index, the \"once\" value will be consumed\nby the set operation, and the mocked property value will be changed to the \"once\" value. This may\nlead to unexpected behavior if you intend the \"once\" value to only be used for a get operation.
",
"displayName": "Caveat"
}
]
},
{
"textRaw": "`ctx.resetAccesses()`",
"name": "resetAccesses",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "Resets the access history of the mocked property.
"
},
{
"textRaw": "`ctx.restore()`",
"name": "restore",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "Resets the implementation of the mock property to its original behavior. The\nmock can still be used after calling this function.
"
}
]
},
{
"textRaw": "Class: `MockTracker`",
"name": "MockTracker",
"type": "class",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"desc": "The MockTracker class is used to manage mocking functionality. The test runner\nmodule provides a top level mock export which is a MockTracker instance.\nEach test also provides its own MockTracker instance via the test context's\nmock property.
",
"methods": [
{
"textRaw": "`mock.fn([original[, implementation]][, options])`",
"name": "fn",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`original` {Function|AsyncFunction} An optional function to create a mock on. **Default:** A no-op function.",
"name": "original",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "An optional function to create a mock on.",
"optional": true
},
{
"textRaw": "`implementation` {Function|AsyncFunction} An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and then restore the behavior of `original`. **Default:** The function specified by `original`.",
"name": "implementation",
"type": "Function|AsyncFunction",
"default": "The function specified by `original`",
"desc": "An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and then restore the behavior of `original`.",
"optional": true
},
{
"textRaw": "`options` {Object} Optional configuration options for the mock function. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Optional configuration options for the mock function. The following properties are supported:",
"options": [
{
"textRaw": "`times` {integer} The number of times that the mock will use the behavior of `implementation`. Once the mock function has been called `times` times, it will automatically restore the behavior of `original`. This value must be an integer greater than zero. **Default:** `Infinity`.",
"name": "times",
"type": "integer",
"default": "`Infinity`",
"desc": "The number of times that the mock will use the behavior of `implementation`. Once the mock function has been called `times` times, it will automatically restore the behavior of `original`. This value must be an integer greater than zero."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Proxy} The mocked function. The mocked function contains a special `mock` property, which is an instance of `MockFunctionContext`, and can be used for inspecting and changing the behavior of the mocked function.",
"name": "return",
"type": "Proxy",
"desc": "The mocked function. The mocked function contains a special `mock` property, which is an instance of `MockFunctionContext`, and can be used for inspecting and changing the behavior of the mocked function."
}
}
],
"desc": "This function is used to create a mock function.
\nThe following example creates a mock function that increments a counter by one\non each invocation. The times option is used to modify the mock behavior such\nthat the first two invocations add two to the counter instead of one.
\ntest('mocks a counting function', (t) => {\n let cnt = 0;\n\n function addOne() {\n cnt++;\n return cnt;\n }\n\n function addTwo() {\n cnt += 2;\n return cnt;\n }\n\n const fn = t.mock.fn(addOne, addTwo, { times: 2 });\n\n assert.strictEqual(fn(), 2);\n assert.strictEqual(fn(), 4);\n assert.strictEqual(fn(), 5);\n assert.strictEqual(fn(), 6);\n});\n
"
},
{
"textRaw": "`mock.getter(object, methodName[, implementation][, options])`",
"name": "getter",
"type": "method",
"meta": {
"added": [
"v19.3.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"name": "object"
},
{
"name": "methodName"
},
{
"name": "implementation",
"optional": true
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "This function is syntax sugar for MockTracker.method with options.getter\nset to true.
"
},
{
"textRaw": "`mock.method(object, methodName[, implementation][, options])`",
"name": "method",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`object` {Object} The object whose method is being mocked.",
"name": "object",
"type": "Object",
"desc": "The object whose method is being mocked."
},
{
"textRaw": "`methodName` {string|symbol} The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown.",
"name": "methodName",
"type": "string|symbol",
"desc": "The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown."
},
{
"textRaw": "`implementation` {Function|AsyncFunction} An optional function used as the mock implementation for `object[methodName]`. **Default:** The original method specified by `object[methodName]`.",
"name": "implementation",
"type": "Function|AsyncFunction",
"default": "The original method specified by `object[methodName]`",
"desc": "An optional function used as the mock implementation for `object[methodName]`.",
"optional": true
},
{
"textRaw": "`options` {Object} Optional configuration options for the mock method. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Optional configuration options for the mock method. The following properties are supported:",
"options": [
{
"textRaw": "`getter` {boolean} If `true`, `object[methodName]` is treated as a getter. This option cannot be used with the `setter` option. **Default:** false.",
"name": "getter",
"type": "boolean",
"default": "false",
"desc": "If `true`, `object[methodName]` is treated as a getter. This option cannot be used with the `setter` option."
},
{
"textRaw": "`setter` {boolean} If `true`, `object[methodName]` is treated as a setter. This option cannot be used with the `getter` option. **Default:** false.",
"name": "setter",
"type": "boolean",
"default": "false",
"desc": "If `true`, `object[methodName]` is treated as a setter. This option cannot be used with the `getter` option."
},
{
"textRaw": "`times` {integer} The number of times that the mock will use the behavior of `implementation`. Once the mocked method has been called `times` times, it will automatically restore the original behavior. This value must be an integer greater than zero. **Default:** `Infinity`.",
"name": "times",
"type": "integer",
"default": "`Infinity`",
"desc": "The number of times that the mock will use the behavior of `implementation`. Once the mocked method has been called `times` times, it will automatically restore the original behavior. This value must be an integer greater than zero."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Proxy} The mocked method. The mocked method contains a special `mock` property, which is an instance of `MockFunctionContext`, and can be used for inspecting and changing the behavior of the mocked method.",
"name": "return",
"type": "Proxy",
"desc": "The mocked method. The mocked method contains a special `mock` property, which is an instance of `MockFunctionContext`, and can be used for inspecting and changing the behavior of the mocked method."
}
}
],
"desc": "This function is used to create a mock on an existing object method. The\nfollowing example demonstrates how a mock is created on an existing object\nmethod.
\ntest('spies on an object method', (t) => {\n const number = {\n value: 5,\n subtract(a) {\n return this.value - a;\n },\n };\n\n t.mock.method(number, 'subtract');\n assert.strictEqual(number.subtract.mock.callCount(), 0);\n assert.strictEqual(number.subtract(3), 2);\n assert.strictEqual(number.subtract.mock.callCount(), 1);\n\n const call = number.subtract.mock.calls[0];\n\n assert.deepStrictEqual(call.arguments, [3]);\n assert.strictEqual(call.result, 2);\n assert.strictEqual(call.error, undefined);\n assert.strictEqual(call.target, undefined);\n assert.strictEqual(call.this, number);\n});\n
"
},
{
"textRaw": "`mock.module(specifier[, options])`",
"name": "module",
"type": "method",
"meta": {
"added": [
"v22.3.0",
"v20.18.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/58007",
"description": "Support JSON modules."
}
]
},
"stability": 1,
"stabilityText": "Early development",
"signatures": [
{
"params": [
{
"textRaw": "`specifier` {string|URL} A string identifying the module to mock.",
"name": "specifier",
"type": "string|URL",
"desc": "A string identifying the module to mock."
},
{
"textRaw": "`options` {Object} Optional configuration options for the mock module. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Optional configuration options for the mock module. The following properties are supported:",
"options": [
{
"textRaw": "`cache` {boolean} If `false`, each call to `require()` or `import()` generates a new mock module. If `true`, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. **Default:** false.",
"name": "cache",
"type": "boolean",
"default": "false",
"desc": "If `false`, each call to `require()` or `import()` generates a new mock module. If `true`, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache."
},
{
"textRaw": "`defaultExport` {any} An optional value used as the mocked module's default export. If this value is not provided, ESM mocks do not include a default export. If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`.",
"name": "defaultExport",
"type": "any",
"desc": "An optional value used as the mocked module's default export. If this value is not provided, ESM mocks do not include a default export. If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`."
},
{
"textRaw": "`namedExports` {Object} An optional object whose keys and values are used to create the named exports of the mock module. If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. Therefore, if a mock is created with both named exports and a non-object default export, the mock will throw an exception when used as a CJS or builtin module.",
"name": "namedExports",
"type": "Object",
"desc": "An optional object whose keys and values are used to create the named exports of the mock module. If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. Therefore, if a mock is created with both named exports and a non-object default export, the mock will throw an exception when used as a CJS or builtin module."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {MockModuleContext} An object that can be used to manipulate the mock.",
"name": "return",
"type": "MockModuleContext",
"desc": "An object that can be used to manipulate the mock."
}
}
],
"desc": "This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and\nNode.js builtin modules. Any references to the original module prior to mocking are not impacted. In\norder to enable module mocking, Node.js must be started with the\n--experimental-test-module-mocks command-line flag.
\nThe following example demonstrates how a mock is created for a module.
\ntest('mocks a builtin module in both module systems', async (t) => {\n // Create a mock of 'node:readline' with a named export named 'fn', which\n // does not exist in the original 'node:readline' module.\n const mock = t.mock.module('node:readline', {\n namedExports: { fn() { return 42; } },\n });\n\n let esmImpl = await import('node:readline');\n let cjsImpl = require('node:readline');\n\n // cursorTo() is an export of the original 'node:readline' module.\n assert.strictEqual(esmImpl.cursorTo, undefined);\n assert.strictEqual(cjsImpl.cursorTo, undefined);\n assert.strictEqual(esmImpl.fn(), 42);\n assert.strictEqual(cjsImpl.fn(), 42);\n\n mock.restore();\n\n // The mock is restored, so the original builtin module is returned.\n esmImpl = await import('node:readline');\n cjsImpl = require('node:readline');\n\n assert.strictEqual(typeof esmImpl.cursorTo, 'function');\n assert.strictEqual(typeof cjsImpl.cursorTo, 'function');\n assert.strictEqual(esmImpl.fn, undefined);\n assert.strictEqual(cjsImpl.fn, undefined);\n});\n
"
},
{
"textRaw": "`mock.property(object, propertyName[, value])`",
"name": "property",
"type": "method",
"meta": {
"added": [
"v24.3.0",
"v22.20.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`object` {Object} The object whose value is being mocked.",
"name": "object",
"type": "Object",
"desc": "The object whose value is being mocked."
},
{
"textRaw": "`propertyName` {string|symbol} The identifier of the property on `object` to mock.",
"name": "propertyName",
"type": "string|symbol",
"desc": "The identifier of the property on `object` to mock."
},
{
"textRaw": "`value` {any} An optional value used as the mock value for `object[propertyName]`. **Default:** The original property value.",
"name": "value",
"type": "any",
"default": "The original property value",
"desc": "An optional value used as the mock value for `object[propertyName]`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Proxy} A proxy to the mocked object. The mocked object contains a special `mock` property, which is an instance of `MockPropertyContext`, and can be used for inspecting and changing the behavior of the mocked property.",
"name": "return",
"type": "Proxy",
"desc": "A proxy to the mocked object. The mocked object contains a special `mock` property, which is an instance of `MockPropertyContext`, and can be used for inspecting and changing the behavior of the mocked property."
}
}
],
"desc": "Creates a mock for a property value on an object. This allows you to track and control access to a specific property,\nincluding how many times it is read (getter) or written (setter), and to restore the original value after mocking.
\ntest('mocks a property value', (t) => {\n const obj = { foo: 42 };\n const prop = t.mock.property(obj, 'foo', 100);\n\n assert.strictEqual(obj.foo, 100);\n assert.strictEqual(prop.mock.accessCount(), 1);\n assert.strictEqual(prop.mock.accesses[0].type, 'get');\n assert.strictEqual(prop.mock.accesses[0].value, 100);\n\n obj.foo = 200;\n assert.strictEqual(prop.mock.accessCount(), 2);\n assert.strictEqual(prop.mock.accesses[1].type, 'set');\n assert.strictEqual(prop.mock.accesses[1].value, 200);\n\n prop.mock.restore();\n assert.strictEqual(obj.foo, 42);\n});\n
"
},
{
"textRaw": "`mock.reset()`",
"name": "reset",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "This function restores the default behavior of all mocks that were previously\ncreated by this MockTracker and disassociates the mocks from the\nMockTracker instance. Once disassociated, the mocks can still be used, but the\nMockTracker instance can no longer be used to reset their behavior or\notherwise interact with them.
\nAfter each test completes, this function is called on the test context's\nMockTracker. If the global MockTracker is used extensively, calling this\nfunction manually is recommended.
"
},
{
"textRaw": "`mock.restoreAll()`",
"name": "restoreAll",
"type": "method",
"meta": {
"added": [
"v19.1.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "This function restores the default behavior of all mocks that were previously\ncreated by this MockTracker. Unlike mock.reset(), mock.restoreAll() does\nnot disassociate the mocks from the MockTracker instance.
"
},
{
"textRaw": "`mock.setter(object, methodName[, implementation][, options])`",
"name": "setter",
"type": "method",
"meta": {
"added": [
"v19.3.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"name": "object"
},
{
"name": "methodName"
},
{
"name": "implementation",
"optional": true
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "This function is syntax sugar for MockTracker.method with options.setter\nset to true.
"
}
]
},
{
"textRaw": "Class: `MockTimers`",
"name": "MockTimers",
"type": "class",
"meta": {
"added": [
"v20.4.0",
"v18.19.0"
],
"changes": [
{
"version": "v23.1.0",
"pr-url": "https://github.com/nodejs/node/pull/55398",
"description": "The Mock Timers is now stable."
}
]
},
"desc": "Mocking timers is a technique commonly used in software testing to simulate and\ncontrol the behavior of timers, such as setInterval and setTimeout,\nwithout actually waiting for the specified time intervals.
\nMockTimers is also able to mock the Date object.
\nThe MockTracker provides a top-level timers export\nwhich is a MockTimers instance.
",
"methods": [
{
"textRaw": "`timers.enable([enableOptions])`",
"name": "enable",
"type": "method",
"meta": {
"added": [
"v20.4.0",
"v18.19.0"
],
"changes": [
{
"version": [
"v21.2.0",
"v20.11.0"
],
"pr-url": "https://github.com/nodejs/node/pull/48638",
"description": "Updated parameters to be an option object with available APIs and the default initial epoch."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`enableOptions` {Object} Optional configuration options for enabling timer mocking. The following properties are supported:",
"name": "enableOptions",
"type": "Object",
"desc": "Optional configuration options for enabling timer mocking. The following properties are supported:",
"options": [
{
"textRaw": "`apis` {Array} An optional array containing the timers to mock. The currently supported timer values are `'setInterval'`, `'setTimeout'`, `'setImmediate'`, and `'Date'`. **Default:** `['setInterval', 'setTimeout', 'setImmediate', 'Date']`. If no array is provided, all time related APIs (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, `'clearTimeout'`, `'setImmediate'`, `'clearImmediate'`, and `'Date'`) will be mocked by default.",
"name": "apis",
"type": "Array",
"default": "`['setInterval', 'setTimeout', 'setImmediate', 'Date']`. If no array is provided, all time related APIs (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, `'clearTimeout'`, `'setImmediate'`, `'clearImmediate'`, and `'Date'`) will be mocked by default",
"desc": "An optional array containing the timers to mock. The currently supported timer values are `'setInterval'`, `'setTimeout'`, `'setImmediate'`, and `'Date'`."
},
{
"textRaw": "`now` {number|Date} An optional number or Date object representing the initial time (in milliseconds) to use as the value for `Date.now()`. **Default:** `0`.",
"name": "now",
"type": "number|Date",
"default": "`0`",
"desc": "An optional number or Date object representing the initial time (in milliseconds) to use as the value for `Date.now()`."
}
],
"optional": true
}
]
}
],
"desc": "Enables timer mocking for the specified timers.
\nNote: When you enable mocking for a specific timer, its associated\nclear function will also be implicitly mocked.
\nNote: Mocking Date will affect the behavior of the mocked timers\nas they use the same internal clock.
\nExample usage without setting initial time:
\nimport { mock } from 'node:test';\nmock.timers.enable({ apis: ['setInterval'] });\n
\nconst { mock } = require('node:test');\nmock.timers.enable({ apis: ['setInterval'] });\n
\nThe above example enables mocking for the setInterval timer and\nimplicitly mocks the clearInterval function. Only the setInterval\nand clearInterval functions from node:timers,\nnode:timers/promises, and\nglobalThis will be mocked.
\nExample usage with initial time set
\nimport { mock } from 'node:test';\nmock.timers.enable({ apis: ['Date'], now: 1000 });\n
\nconst { mock } = require('node:test');\nmock.timers.enable({ apis: ['Date'], now: 1000 });\n
\nExample usage with initial Date object as time set
\nimport { mock } from 'node:test';\nmock.timers.enable({ apis: ['Date'], now: new Date() });\n
\nconst { mock } = require('node:test');\nmock.timers.enable({ apis: ['Date'], now: new Date() });\n
\nAlternatively, if you call mock.timers.enable() without any parameters:
\nAll timers ('setInterval', 'clearInterval', 'setTimeout', 'clearTimeout',\n'setImmediate', and 'clearImmediate') will be mocked. The setInterval,\nclearInterval, setTimeout, clearTimeout, setImmediate, and\nclearImmediate functions from node:timers, node:timers/promises, and\nglobalThis will be mocked. As well as the global Date object.
"
},
{
"textRaw": "`timers.reset()`",
"name": "reset",
"type": "method",
"meta": {
"added": [
"v20.4.0",
"v18.19.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "This function restores the default behavior of all mocks that were previously\ncreated by this MockTimers instance and disassociates the mocks\nfrom the MockTracker instance.
\nNote: After each test completes, this function is called on\nthe test context's MockTracker.
\nimport { mock } from 'node:test';\nmock.timers.reset();\n
\nconst { mock } = require('node:test');\nmock.timers.reset();\n
"
},
{
"textRaw": "`timers[Symbol.dispose]()`",
"name": "[Symbol.dispose]",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "Calls timers.reset().
"
},
{
"textRaw": "`timers.tick([milliseconds])`",
"name": "tick",
"type": "method",
"meta": {
"added": [
"v20.4.0",
"v18.19.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`milliseconds` {number} The amount of time, in milliseconds, to advance the timers. **Default:** `1`.",
"name": "milliseconds",
"type": "number",
"default": "`1`",
"desc": "The amount of time, in milliseconds, to advance the timers.",
"optional": true
}
]
}
],
"desc": "Advances time for all mocked timers.
\nNote: This diverges from how setTimeout in Node.js behaves and accepts\nonly positive numbers. In Node.js, setTimeout with negative numbers is\nonly supported for web compatibility reasons.
\nThe following example mocks a setTimeout function and\nby using .tick advances in\ntime triggering all pending timers.
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n\n context.mock.timers.enable({ apis: ['setTimeout'] });\n\n setTimeout(fn, 9999);\n\n assert.strictEqual(fn.mock.callCount(), 0);\n\n // Advance in time\n context.mock.timers.tick(9999);\n\n assert.strictEqual(fn.mock.callCount(), 1);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n context.mock.timers.enable({ apis: ['setTimeout'] });\n\n setTimeout(fn, 9999);\n assert.strictEqual(fn.mock.callCount(), 0);\n\n // Advance in time\n context.mock.timers.tick(9999);\n\n assert.strictEqual(fn.mock.callCount(), 1);\n});\n
\nAlternatively, the .tick function can be called many times
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n context.mock.timers.enable({ apis: ['setTimeout'] });\n const nineSecs = 9000;\n setTimeout(fn, nineSecs);\n\n const threeSeconds = 3000;\n context.mock.timers.tick(threeSeconds);\n context.mock.timers.tick(threeSeconds);\n context.mock.timers.tick(threeSeconds);\n\n assert.strictEqual(fn.mock.callCount(), 1);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n context.mock.timers.enable({ apis: ['setTimeout'] });\n const nineSecs = 9000;\n setTimeout(fn, nineSecs);\n\n const threeSeconds = 3000;\n context.mock.timers.tick(threeSeconds);\n context.mock.timers.tick(threeSeconds);\n context.mock.timers.tick(threeSeconds);\n\n assert.strictEqual(fn.mock.callCount(), 1);\n});\n
\nAdvancing time using .tick will also advance the time for any Date object\ncreated after the mock was enabled (if Date was also set to be mocked).
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n setTimeout(fn, 9999);\n\n assert.strictEqual(fn.mock.callCount(), 0);\n assert.strictEqual(Date.now(), 0);\n\n // Advance in time\n context.mock.timers.tick(9999);\n assert.strictEqual(fn.mock.callCount(), 1);\n assert.strictEqual(Date.now(), 9999);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n\n setTimeout(fn, 9999);\n assert.strictEqual(fn.mock.callCount(), 0);\n assert.strictEqual(Date.now(), 0);\n\n // Advance in time\n context.mock.timers.tick(9999);\n assert.strictEqual(fn.mock.callCount(), 1);\n assert.strictEqual(Date.now(), 9999);\n});\n
",
"modules": [
{
"textRaw": "Using clear functions",
"name": "using_clear_functions",
"type": "module",
"desc": "As mentioned, all clear functions from timers (clearTimeout, clearInterval,and\nclearImmediate) are implicitly mocked. Take a look at this example using setTimeout:
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout'] });\n const id = setTimeout(fn, 9999);\n\n // Implicitly mocked as well\n clearTimeout(id);\n context.mock.timers.tick(9999);\n\n // As that setTimeout was cleared the mock function will never be called\n assert.strictEqual(fn.mock.callCount(), 0);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {\n const fn = context.mock.fn();\n\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout'] });\n const id = setTimeout(fn, 9999);\n\n // Implicitly mocked as well\n clearTimeout(id);\n context.mock.timers.tick(9999);\n\n // As that setTimeout was cleared the mock function will never be called\n assert.strictEqual(fn.mock.callCount(), 0);\n});\n
",
"displayName": "Using clear functions"
},
{
"textRaw": "Working with Node.js timers modules",
"name": "working_with_node.js_timers_modules",
"type": "module",
"desc": "Once you enable mocking timers, node:timers,\nnode:timers/promises modules,\nand timers from the Node.js global context are enabled:
\nNote: Destructuring functions such as\nimport { setTimeout } from 'node:timers' is currently\nnot supported by this API.
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\nimport nodeTimers from 'node:timers';\nimport nodeTimersPromises from 'node:timers/promises';\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', async (context) => {\n const globalTimeoutObjectSpy = context.mock.fn();\n const nodeTimerSpy = context.mock.fn();\n const nodeTimerPromiseSpy = context.mock.fn();\n\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout'] });\n setTimeout(globalTimeoutObjectSpy, 9999);\n nodeTimers.setTimeout(nodeTimerSpy, 9999);\n\n const promise = nodeTimersPromises.setTimeout(9999).then(nodeTimerPromiseSpy);\n\n // Advance in time\n context.mock.timers.tick(9999);\n assert.strictEqual(globalTimeoutObjectSpy.mock.callCount(), 1);\n assert.strictEqual(nodeTimerSpy.mock.callCount(), 1);\n await promise;\n assert.strictEqual(nodeTimerPromiseSpy.mock.callCount(), 1);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\nconst nodeTimers = require('node:timers');\nconst nodeTimersPromises = require('node:timers/promises');\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', async (context) => {\n const globalTimeoutObjectSpy = context.mock.fn();\n const nodeTimerSpy = context.mock.fn();\n const nodeTimerPromiseSpy = context.mock.fn();\n\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout'] });\n setTimeout(globalTimeoutObjectSpy, 9999);\n nodeTimers.setTimeout(nodeTimerSpy, 9999);\n\n const promise = nodeTimersPromises.setTimeout(9999).then(nodeTimerPromiseSpy);\n\n // Advance in time\n context.mock.timers.tick(9999);\n assert.strictEqual(globalTimeoutObjectSpy.mock.callCount(), 1);\n assert.strictEqual(nodeTimerSpy.mock.callCount(), 1);\n await promise;\n assert.strictEqual(nodeTimerPromiseSpy.mock.callCount(), 1);\n});\n
\nIn Node.js, setInterval from node:timers/promises\nis an AsyncGenerator and is also supported by this API:
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\nimport nodeTimersPromises from 'node:timers/promises';\ntest('should tick five times testing a real use case', async (context) => {\n context.mock.timers.enable({ apis: ['setInterval'] });\n\n const expectedIterations = 3;\n const interval = 1000;\n const startedAt = Date.now();\n async function run() {\n const times = [];\n for await (const time of nodeTimersPromises.setInterval(interval, startedAt)) {\n times.push(time);\n if (times.length === expectedIterations) break;\n }\n return times;\n }\n\n const r = run();\n context.mock.timers.tick(interval);\n context.mock.timers.tick(interval);\n context.mock.timers.tick(interval);\n\n const timeResults = await r;\n assert.strictEqual(timeResults.length, expectedIterations);\n for (let it = 1; it < expectedIterations; it++) {\n assert.strictEqual(timeResults[it - 1], startedAt + (interval * it));\n }\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\nconst nodeTimersPromises = require('node:timers/promises');\ntest('should tick five times testing a real use case', async (context) => {\n context.mock.timers.enable({ apis: ['setInterval'] });\n\n const expectedIterations = 3;\n const interval = 1000;\n const startedAt = Date.now();\n async function run() {\n const times = [];\n for await (const time of nodeTimersPromises.setInterval(interval, startedAt)) {\n times.push(time);\n if (times.length === expectedIterations) break;\n }\n return times;\n }\n\n const r = run();\n context.mock.timers.tick(interval);\n context.mock.timers.tick(interval);\n context.mock.timers.tick(interval);\n\n const timeResults = await r;\n assert.strictEqual(timeResults.length, expectedIterations);\n for (let it = 1; it < expectedIterations; it++) {\n assert.strictEqual(timeResults[it - 1], startedAt + (interval * it));\n }\n});\n
",
"displayName": "Working with Node.js timers modules"
}
]
},
{
"textRaw": "`timers.runAll()`",
"name": "runAll",
"type": "method",
"meta": {
"added": [
"v20.4.0",
"v18.19.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Triggers all pending mocked timers immediately. If the Date object is also\nmocked, it will also advance the Date object to the furthest timer's time.
\nThe example below triggers all pending timers immediately,\ncausing them to execute without any delay.
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('runAll functions following the given order', (context) => {\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const results = [];\n setTimeout(() => results.push(1), 9999);\n\n // Notice that if both timers have the same timeout,\n // the order of execution is guaranteed\n setTimeout(() => results.push(3), 8888);\n setTimeout(() => results.push(2), 8888);\n\n assert.deepStrictEqual(results, []);\n\n context.mock.timers.runAll();\n assert.deepStrictEqual(results, [3, 2, 1]);\n // The Date object is also advanced to the furthest timer's time\n assert.strictEqual(Date.now(), 9999);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('runAll functions following the given order', (context) => {\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const results = [];\n setTimeout(() => results.push(1), 9999);\n\n // Notice that if both timers have the same timeout,\n // the order of execution is guaranteed\n setTimeout(() => results.push(3), 8888);\n setTimeout(() => results.push(2), 8888);\n\n assert.deepStrictEqual(results, []);\n\n context.mock.timers.runAll();\n assert.deepStrictEqual(results, [3, 2, 1]);\n // The Date object is also advanced to the furthest timer's time\n assert.strictEqual(Date.now(), 9999);\n});\n
\nNote: The runAll() function is specifically designed for\ntriggering timers in the context of timer mocking.\nIt does not have any effect on real-time system\nclocks or actual timers outside of the mocking environment.
"
},
{
"textRaw": "`timers.setTime(milliseconds)`",
"name": "setTime",
"type": "method",
"meta": {
"added": [
"v21.2.0",
"v20.11.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"name": "milliseconds"
}
]
}
],
"desc": "Sets the current Unix timestamp that will be used as reference for any mocked\nDate objects.
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('runAll functions following the given order', (context) => {\n const now = Date.now();\n const setTime = 1000;\n // Date.now is not mocked\n assert.deepStrictEqual(Date.now(), now);\n\n context.mock.timers.enable({ apis: ['Date'] });\n context.mock.timers.setTime(setTime);\n // Date.now is now 1000\n assert.strictEqual(Date.now(), setTime);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('setTime replaces current time', (context) => {\n const now = Date.now();\n const setTime = 1000;\n // Date.now is not mocked\n assert.deepStrictEqual(Date.now(), now);\n\n context.mock.timers.enable({ apis: ['Date'] });\n context.mock.timers.setTime(setTime);\n // Date.now is now 1000\n assert.strictEqual(Date.now(), setTime);\n});\n
",
"modules": [
{
"textRaw": "Dates and Timers working together",
"name": "dates_and_timers_working_together",
"type": "module",
"desc": "Dates and timer objects are dependent on each other. If you use setTime() to\npass the current time to the mocked Date object, the set timers with\nsetTimeout and setInterval will not be affected.
\nHowever, the tick method will advance the mocked Date object.
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('runAll functions following the given order', (context) => {\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const results = [];\n setTimeout(() => results.push(1), 9999);\n\n assert.deepStrictEqual(results, []);\n context.mock.timers.setTime(12000);\n assert.deepStrictEqual(results, []);\n // The date is advanced but the timers don't tick\n assert.strictEqual(Date.now(), 12000);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('runAll functions following the given order', (context) => {\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const results = [];\n setTimeout(() => results.push(1), 9999);\n\n assert.deepStrictEqual(results, []);\n context.mock.timers.setTime(12000);\n assert.deepStrictEqual(results, []);\n // The date is advanced but the timers don't tick\n assert.strictEqual(Date.now(), 12000);\n});\n
",
"displayName": "Dates and Timers working together"
}
]
}
]
},
{
"textRaw": "Class: `TestsStream`",
"name": "TestsStream",
"type": "class",
"meta": {
"added": [
"v18.9.0",
"v16.19.0"
],
"changes": [
{
"version": [
"v20.0.0",
"v19.9.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/47094",
"description": "added type to test:pass and test:fail events for when the test is a suite."
}
]
},
"desc": "\nA successful call to run() method will return a new <TestsStream>\nobject, streaming a series of events representing the execution of the tests. TestsStream will emit events, in the order of the tests definition
\nSome of the events are guaranteed to be emitted in the same order as the tests\nare defined, while others are emitted in the order that the tests execute.
",
"events": [
{
"textRaw": "Event: `'test:coverage'`",
"name": "test:coverage",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`summary` {Object} An object containing the coverage report.",
"name": "summary",
"type": "Object",
"desc": "An object containing the coverage report.",
"options": [
{
"textRaw": "`files` {Array} An array of coverage reports for individual files. Each report is an object with the following schema:",
"name": "files",
"type": "Array",
"desc": "An array of coverage reports for individual files. Each report is an object with the following schema:",
"options": [
{
"textRaw": "`path` {string} The absolute path of the file.",
"name": "path",
"type": "string",
"desc": "The absolute path of the file."
},
{
"textRaw": "`totalLineCount` {number} The total number of lines.",
"name": "totalLineCount",
"type": "number",
"desc": "The total number of lines."
},
{
"textRaw": "`totalBranchCount` {number} The total number of branches.",
"name": "totalBranchCount",
"type": "number",
"desc": "The total number of branches."
},
{
"textRaw": "`totalFunctionCount` {number} The total number of functions.",
"name": "totalFunctionCount",
"type": "number",
"desc": "The total number of functions."
},
{
"textRaw": "`coveredLineCount` {number} The number of covered lines.",
"name": "coveredLineCount",
"type": "number",
"desc": "The number of covered lines."
},
{
"textRaw": "`coveredBranchCount` {number} The number of covered branches.",
"name": "coveredBranchCount",
"type": "number",
"desc": "The number of covered branches."
},
{
"textRaw": "`coveredFunctionCount` {number} The number of covered functions.",
"name": "coveredFunctionCount",
"type": "number",
"desc": "The number of covered functions."
},
{
"textRaw": "`coveredLinePercent` {number} The percentage of lines covered.",
"name": "coveredLinePercent",
"type": "number",
"desc": "The percentage of lines covered."
},
{
"textRaw": "`coveredBranchPercent` {number} The percentage of branches covered.",
"name": "coveredBranchPercent",
"type": "number",
"desc": "The percentage of branches covered."
},
{
"textRaw": "`coveredFunctionPercent` {number} The percentage of functions covered.",
"name": "coveredFunctionPercent",
"type": "number",
"desc": "The percentage of functions covered."
},
{
"textRaw": "`functions` {Array} An array of functions representing function coverage.",
"name": "functions",
"type": "Array",
"desc": "An array of functions representing function coverage.",
"options": [
{
"textRaw": "`name` {string} The name of the function.",
"name": "name",
"type": "string",
"desc": "The name of the function."
},
{
"textRaw": "`line` {number} The line number where the function is defined.",
"name": "line",
"type": "number",
"desc": "The line number where the function is defined."
},
{
"textRaw": "`count` {number} The number of times the function was called.",
"name": "count",
"type": "number",
"desc": "The number of times the function was called."
}
]
},
{
"textRaw": "`branches` {Array} An array of branches representing branch coverage.",
"name": "branches",
"type": "Array",
"desc": "An array of branches representing branch coverage.",
"options": [
{
"textRaw": "`line` {number} The line number where the branch is defined.",
"name": "line",
"type": "number",
"desc": "The line number where the branch is defined."
},
{
"textRaw": "`count` {number} The number of times the branch was taken.",
"name": "count",
"type": "number",
"desc": "The number of times the branch was taken."
}
]
},
{
"textRaw": "`lines` {Array} An array of lines representing line numbers and the number of times they were covered.",
"name": "lines",
"type": "Array",
"desc": "An array of lines representing line numbers and the number of times they were covered.",
"options": [
{
"textRaw": "`line` {number} The line number.",
"name": "line",
"type": "number",
"desc": "The line number."
},
{
"textRaw": "`count` {number} The number of times the line was covered.",
"name": "count",
"type": "number",
"desc": "The number of times the line was covered."
}
]
}
]
},
{
"textRaw": "`thresholds` {Object} An object containing whether or not the coverage for each coverage type.",
"name": "thresholds",
"type": "Object",
"desc": "An object containing whether or not the coverage for each coverage type.",
"options": [
{
"textRaw": "`function` {number} The function coverage threshold.",
"name": "function",
"type": "number",
"desc": "The function coverage threshold."
},
{
"textRaw": "`branch` {number} The branch coverage threshold.",
"name": "branch",
"type": "number",
"desc": "The branch coverage threshold."
},
{
"textRaw": "`line` {number} The line coverage threshold.",
"name": "line",
"type": "number",
"desc": "The line coverage threshold."
}
]
},
{
"textRaw": "`totals` {Object} An object containing a summary of coverage for all files.",
"name": "totals",
"type": "Object",
"desc": "An object containing a summary of coverage for all files.",
"options": [
{
"textRaw": "`totalLineCount` {number} The total number of lines.",
"name": "totalLineCount",
"type": "number",
"desc": "The total number of lines."
},
{
"textRaw": "`totalBranchCount` {number} The total number of branches.",
"name": "totalBranchCount",
"type": "number",
"desc": "The total number of branches."
},
{
"textRaw": "`totalFunctionCount` {number} The total number of functions.",
"name": "totalFunctionCount",
"type": "number",
"desc": "The total number of functions."
},
{
"textRaw": "`coveredLineCount` {number} The number of covered lines.",
"name": "coveredLineCount",
"type": "number",
"desc": "The number of covered lines."
},
{
"textRaw": "`coveredBranchCount` {number} The number of covered branches.",
"name": "coveredBranchCount",
"type": "number",
"desc": "The number of covered branches."
},
{
"textRaw": "`coveredFunctionCount` {number} The number of covered functions.",
"name": "coveredFunctionCount",
"type": "number",
"desc": "The number of covered functions."
},
{
"textRaw": "`coveredLinePercent` {number} The percentage of lines covered.",
"name": "coveredLinePercent",
"type": "number",
"desc": "The percentage of lines covered."
},
{
"textRaw": "`coveredBranchPercent` {number} The percentage of branches covered.",
"name": "coveredBranchPercent",
"type": "number",
"desc": "The percentage of branches covered."
},
{
"textRaw": "`coveredFunctionPercent` {number} The percentage of functions covered.",
"name": "coveredFunctionPercent",
"type": "number",
"desc": "The percentage of functions covered."
}
]
},
{
"textRaw": "`workingDirectory` {string} The working directory when code coverage began. This is useful for displaying relative path names in case the tests changed the working directory of the Node.js process.",
"name": "workingDirectory",
"type": "string",
"desc": "The working directory when code coverage began. This is useful for displaying relative path names in case the tests changed the working directory of the Node.js process."
}
]
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
}
]
}
],
"desc": "Emitted when code coverage is enabled and all tests have completed.
"
},
{
"textRaw": "Event: `'test:complete'`",
"name": "test:complete",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`details` {Object} Additional execution metadata.",
"name": "details",
"type": "Object",
"desc": "Additional execution metadata.",
"options": [
{
"textRaw": "`passed` {boolean} Whether the test passed or not.",
"name": "passed",
"type": "boolean",
"desc": "Whether the test passed or not."
},
{
"textRaw": "`duration_ms` {number} The duration of the test in milliseconds.",
"name": "duration_ms",
"type": "number",
"desc": "The duration of the test in milliseconds."
},
{
"textRaw": "`error` {Error|undefined} An error wrapping the error thrown by the test if it did not pass.",
"name": "error",
"type": "Error|undefined",
"desc": "An error wrapping the error thrown by the test if it did not pass.",
"options": [
{
"textRaw": "`cause` {Error} The actual error thrown by the test.",
"name": "cause",
"type": "Error",
"desc": "The actual error thrown by the test."
}
]
},
{
"textRaw": "`type` {string|undefined} The type of the test, used to denote whether this is a suite.",
"name": "type",
"type": "string|undefined",
"desc": "The type of the test, used to denote whether this is a suite."
}
]
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`name` {string} The test name.",
"name": "name",
"type": "string",
"desc": "The test name."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
},
{
"textRaw": "`testNumber` {number} The ordinal number of the test.",
"name": "testNumber",
"type": "number",
"desc": "The ordinal number of the test."
},
{
"textRaw": "`todo` {string|boolean|undefined} Present if `context.todo` is called",
"name": "todo",
"type": "string|boolean|undefined",
"desc": "Present if `context.todo` is called"
},
{
"textRaw": "`skip` {string|boolean|undefined} Present if `context.skip` is called",
"name": "skip",
"type": "string|boolean|undefined",
"desc": "Present if `context.skip` is called"
}
]
}
],
"desc": "Emitted when a test completes its execution.\nThis event is not emitted in the same order as the tests are\ndefined.\nThe corresponding declaration ordered events are 'test:pass' and 'test:fail'.
"
},
{
"textRaw": "Event: `'test:dequeue'`",
"name": "test:dequeue",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`name` {string} The test name.",
"name": "name",
"type": "string",
"desc": "The test name."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
},
{
"textRaw": "`type` {string} The test type. Either `'suite'` or `'test'`.",
"name": "type",
"type": "string",
"desc": "The test type. Either `'suite'` or `'test'`."
}
]
}
],
"desc": "Emitted when a test is dequeued, right before it is executed.\nThis event is not guaranteed to be emitted in the same order as the tests are\ndefined. The corresponding declaration ordered event is 'test:start'.
"
},
{
"textRaw": "Event: `'test:diagnostic'`",
"name": "test:diagnostic",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`message` {string} The diagnostic message.",
"name": "message",
"type": "string",
"desc": "The diagnostic message."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
},
{
"textRaw": "`level` {string} The severity level of the diagnostic message. Possible values are:",
"name": "level",
"type": "string",
"desc": "The severity level of the diagnostic message. Possible values are:",
"options": [
{
"textRaw": "`'info'`: Informational messages.",
"desc": "`'info'`: Informational messages."
},
{
"textRaw": "`'warn'`: Warnings.",
"desc": "`'warn'`: Warnings."
},
{
"textRaw": "`'error'`: Errors.",
"desc": "`'error'`: Errors."
}
]
}
]
}
],
"desc": "Emitted when context.diagnostic is called.\nThis event is guaranteed to be emitted in the same order as the tests are\ndefined.
"
},
{
"textRaw": "Event: `'test:enqueue'`",
"name": "test:enqueue",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`name` {string} The test name.",
"name": "name",
"type": "string",
"desc": "The test name."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
},
{
"textRaw": "`type` {string} The test type. Either `'suite'` or `'test'`.",
"name": "type",
"type": "string",
"desc": "The test type. Either `'suite'` or `'test'`."
}
]
}
],
"desc": "Emitted when a test is enqueued for execution.
"
},
{
"textRaw": "Event: `'test:fail'`",
"name": "test:fail",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`details` {Object} Additional execution metadata.",
"name": "details",
"type": "Object",
"desc": "Additional execution metadata.",
"options": [
{
"textRaw": "`duration_ms` {number} The duration of the test in milliseconds.",
"name": "duration_ms",
"type": "number",
"desc": "The duration of the test in milliseconds."
},
{
"textRaw": "`error` {Error} An error wrapping the error thrown by the test.",
"name": "error",
"type": "Error",
"desc": "An error wrapping the error thrown by the test.",
"options": [
{
"textRaw": "`cause` {Error} The actual error thrown by the test.",
"name": "cause",
"type": "Error",
"desc": "The actual error thrown by the test."
}
]
},
{
"textRaw": "`type` {string|undefined} The type of the test, used to denote whether this is a suite.",
"name": "type",
"type": "string|undefined",
"desc": "The type of the test, used to denote whether this is a suite."
},
{
"textRaw": "`attempt` {number|undefined} The attempt number of the test run, present only when using the `--test-rerun-failures` flag.",
"name": "attempt",
"type": "number|undefined",
"desc": "The attempt number of the test run, present only when using the `--test-rerun-failures` flag."
}
]
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`name` {string} The test name.",
"name": "name",
"type": "string",
"desc": "The test name."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
},
{
"textRaw": "`testNumber` {number} The ordinal number of the test.",
"name": "testNumber",
"type": "number",
"desc": "The ordinal number of the test."
},
{
"textRaw": "`todo` {string|boolean|undefined} Present if `context.todo` is called",
"name": "todo",
"type": "string|boolean|undefined",
"desc": "Present if `context.todo` is called"
},
{
"textRaw": "`skip` {string|boolean|undefined} Present if `context.skip` is called",
"name": "skip",
"type": "string|boolean|undefined",
"desc": "Present if `context.skip` is called"
}
]
}
],
"desc": "Emitted when a test fails.\nThis event is guaranteed to be emitted in the same order as the tests are\ndefined.\nThe corresponding execution ordered event is 'test:complete'.
"
},
{
"textRaw": "Event: `'test:interrupted'`",
"name": "test:interrupted",
"type": "event",
"meta": {
"added": [
"v25.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`tests` {Array} An array of objects containing information about the interrupted tests.",
"name": "tests",
"type": "Array",
"desc": "An array of objects containing information about the interrupted tests.",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`name` {string} The test name.",
"name": "name",
"type": "string",
"desc": "The test name."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
}
]
}
]
}
],
"desc": "Emitted when the test runner is interrupted by a SIGINT signal (e.g., when\npressing Ctrl+C). The event contains information about\nthe tests that were running at the time of interruption.
\nWhen using process isolation (the default), the test name will be the file path\nsince the parent runner only knows about file-level tests. When using\n--test-isolation=none, the actual test name is shown.
"
},
{
"textRaw": "Event: `'test:pass'`",
"name": "test:pass",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`details` {Object} Additional execution metadata.",
"name": "details",
"type": "Object",
"desc": "Additional execution metadata.",
"options": [
{
"textRaw": "`duration_ms` {number} The duration of the test in milliseconds.",
"name": "duration_ms",
"type": "number",
"desc": "The duration of the test in milliseconds."
},
{
"textRaw": "`type` {string|undefined} The type of the test, used to denote whether this is a suite.",
"name": "type",
"type": "string|undefined",
"desc": "The type of the test, used to denote whether this is a suite."
},
{
"textRaw": "`attempt` {number|undefined} The attempt number of the test run, present only when using the `--test-rerun-failures` flag.",
"name": "attempt",
"type": "number|undefined",
"desc": "The attempt number of the test run, present only when using the `--test-rerun-failures` flag."
},
{
"textRaw": "`passed_on_attempt` {number|undefined} The attempt number the test passed on, present only when using the `--test-rerun-failures` flag.",
"name": "passed_on_attempt",
"type": "number|undefined",
"desc": "The attempt number the test passed on, present only when using the `--test-rerun-failures` flag."
}
]
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`name` {string} The test name.",
"name": "name",
"type": "string",
"desc": "The test name."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
},
{
"textRaw": "`testNumber` {number} The ordinal number of the test.",
"name": "testNumber",
"type": "number",
"desc": "The ordinal number of the test."
},
{
"textRaw": "`todo` {string|boolean|undefined} Present if `context.todo` is called",
"name": "todo",
"type": "string|boolean|undefined",
"desc": "Present if `context.todo` is called"
},
{
"textRaw": "`skip` {string|boolean|undefined} Present if `context.skip` is called",
"name": "skip",
"type": "string|boolean|undefined",
"desc": "Present if `context.skip` is called"
}
]
}
],
"desc": "Emitted when a test passes.\nThis event is guaranteed to be emitted in the same order as the tests are\ndefined.\nThe corresponding execution ordered event is 'test:complete'.
"
},
{
"textRaw": "Event: `'test:plan'`",
"name": "test:plan",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
},
{
"textRaw": "`count` {number} The number of subtests that have ran.",
"name": "count",
"type": "number",
"desc": "The number of subtests that have ran."
}
]
}
],
"desc": "Emitted when all subtests have completed for a given test.\nThis event is guaranteed to be emitted in the same order as the tests are\ndefined.
"
},
{
"textRaw": "Event: `'test:start'`",
"name": "test:start",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`column` {number|undefined} The column number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "column",
"type": "number|undefined",
"desc": "The column number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`file` {string|undefined} The path of the test file, `undefined` if test was run through the REPL.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file, `undefined` if test was run through the REPL."
},
{
"textRaw": "`line` {number|undefined} The line number where the test is defined, or `undefined` if the test was run through the REPL.",
"name": "line",
"type": "number|undefined",
"desc": "The line number where the test is defined, or `undefined` if the test was run through the REPL."
},
{
"textRaw": "`name` {string} The test name.",
"name": "name",
"type": "string",
"desc": "The test name."
},
{
"textRaw": "`nesting` {number} The nesting level of the test.",
"name": "nesting",
"type": "number",
"desc": "The nesting level of the test."
}
]
}
],
"desc": "Emitted when a test starts reporting its own and its subtests status.\nThis event is guaranteed to be emitted in the same order as the tests are\ndefined.\nThe corresponding execution ordered event is 'test:dequeue'.
"
},
{
"textRaw": "Event: `'test:stderr'`",
"name": "test:stderr",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`file` {string} The path of the test file.",
"name": "file",
"type": "string",
"desc": "The path of the test file."
},
{
"textRaw": "`message` {string} The message written to `stderr`.",
"name": "message",
"type": "string",
"desc": "The message written to `stderr`."
}
]
}
],
"desc": "Emitted when a running test writes to stderr.\nThis event is only emitted if --test flag is passed.\nThis event is not guaranteed to be emitted in the same order as the tests are\ndefined.
"
},
{
"textRaw": "Event: `'test:stdout'`",
"name": "test:stdout",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`file` {string} The path of the test file.",
"name": "file",
"type": "string",
"desc": "The path of the test file."
},
{
"textRaw": "`message` {string} The message written to `stdout`.",
"name": "message",
"type": "string",
"desc": "The message written to `stdout`."
}
]
}
],
"desc": "Emitted when a running test writes to stdout.\nThis event is only emitted if --test flag is passed.\nThis event is not guaranteed to be emitted in the same order as the tests are\ndefined.
"
},
{
"textRaw": "Event: `'test:summary'`",
"name": "test:summary",
"type": "event",
"params": [
{
"textRaw": "`data` {Object}",
"name": "data",
"type": "Object",
"options": [
{
"textRaw": "`counts` {Object} An object containing the counts of various test results.",
"name": "counts",
"type": "Object",
"desc": "An object containing the counts of various test results.",
"options": [
{
"textRaw": "`cancelled` {number} The total number of cancelled tests.",
"name": "cancelled",
"type": "number",
"desc": "The total number of cancelled tests."
},
{
"textRaw": "`failed` {number} The total number of failed tests.",
"name": "failed",
"type": "number",
"desc": "The total number of failed tests."
},
{
"textRaw": "`passed` {number} The total number of passed tests.",
"name": "passed",
"type": "number",
"desc": "The total number of passed tests."
},
{
"textRaw": "`skipped` {number} The total number of skipped tests.",
"name": "skipped",
"type": "number",
"desc": "The total number of skipped tests."
},
{
"textRaw": "`suites` {number} The total number of suites run.",
"name": "suites",
"type": "number",
"desc": "The total number of suites run."
},
{
"textRaw": "`tests` {number} The total number of tests run, excluding suites.",
"name": "tests",
"type": "number",
"desc": "The total number of tests run, excluding suites."
},
{
"textRaw": "`todo` {number} The total number of TODO tests.",
"name": "todo",
"type": "number",
"desc": "The total number of TODO tests."
},
{
"textRaw": "`topLevel` {number} The total number of top level tests and suites.",
"name": "topLevel",
"type": "number",
"desc": "The total number of top level tests and suites."
}
]
},
{
"textRaw": "`duration_ms` {number} The duration of the test run in milliseconds.",
"name": "duration_ms",
"type": "number",
"desc": "The duration of the test run in milliseconds."
},
{
"textRaw": "`file` {string|undefined} The path of the test file that generated the summary. If the summary corresponds to multiple files, this value is `undefined`.",
"name": "file",
"type": "string|undefined",
"desc": "The path of the test file that generated the summary. If the summary corresponds to multiple files, this value is `undefined`."
},
{
"textRaw": "`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`.",
"name": "success",
"type": "boolean",
"desc": "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`."
}
]
}
],
"desc": "Emitted when a test run completes. This event contains metrics pertaining to\nthe completed test run, and is useful for determining if a test run passed or\nfailed. If process-level test isolation is used, a 'test:summary' event is\ngenerated for each test file in addition to a final cumulative summary.
"
},
{
"textRaw": "Event: `'test:watch:drained'`",
"name": "test:watch:drained",
"type": "event",
"params": [],
"desc": "Emitted when no more tests are queued for execution in watch mode.
"
},
{
"textRaw": "Event: `'test:watch:restarted'`",
"name": "test:watch:restarted",
"type": "event",
"params": [],
"desc": "Emitted when one or more tests are restarted due to a file change in watch mode.
"
}
]
},
{
"textRaw": "Class: `TestContext`",
"name": "TestContext",
"type": "class",
"meta": {
"added": [
"v18.0.0",
"v16.17.0"
],
"changes": [
{
"version": [
"v20.1.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/47586",
"description": "The `before` function was added to TestContext."
}
]
},
"desc": "An instance of TestContext is passed to each test function in order to\ninteract with the test runner. However, the TestContext constructor is not\nexposed as part of the API.
",
"methods": [
{
"textRaw": "`context.before([fn][, options])`",
"name": "before",
"type": "method",
"meta": {
"added": [
"v20.1.0",
"v18.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function is used to create a hook running before\nsubtest of the current test.
"
},
{
"textRaw": "`context.beforeEach([fn][, options])`",
"name": "beforeEach",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function is used to create a hook running\nbefore each subtest of the current test.
\ntest('top level test', async (t) => {\n t.beforeEach((t) => t.diagnostic(`about to run ${t.name}`));\n await t.test(\n 'This is a subtest',\n (t) => {\n // Some relevant assertion here\n },\n );\n});\n
"
},
{
"textRaw": "`context.after([fn][, options])`",
"name": "after",
"type": "method",
"meta": {
"added": [
"v19.3.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function is used to create a hook that runs after the current test\nfinishes.
\ntest('top level test', async (t) => {\n t.after((t) => t.diagnostic(`finished running ${t.name}`));\n // Some relevant assertion here\n});\n
"
},
{
"textRaw": "`context.afterEach([fn][, options])`",
"name": "afterEach",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "The hook function. The first argument to this function is a `TestContext` object. If the hook uses callbacks, the callback function is passed as the second argument.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the hook. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the hook. The following properties are supported:",
"options": [
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress hook.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress hook."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent."
}
],
"optional": true
}
]
}
],
"desc": "This function is used to create a hook running\nafter each subtest of the current test.
\ntest('top level test', async (t) => {\n t.afterEach((t) => t.diagnostic(`finished running ${t.name}`));\n await t.test(\n 'This is a subtest',\n (t) => {\n // Some relevant assertion here\n },\n );\n});\n
"
},
{
"textRaw": "`context.diagnostic(message)`",
"name": "diagnostic",
"type": "method",
"meta": {
"added": [
"v18.0.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`message` {string} Message to be reported.",
"name": "message",
"type": "string",
"desc": "Message to be reported."
}
]
}
],
"desc": "This function is used to write diagnostics to the output. Any diagnostic\ninformation is included at the end of the test's results. This function does\nnot return a value.
\ntest('top level test', (t) => {\n t.diagnostic('A diagnostic message');\n});\n
"
},
{
"textRaw": "`context.plan(count[,options])`",
"name": "plan",
"type": "method",
"meta": {
"added": [
"v22.2.0",
"v20.15.0"
],
"changes": [
{
"version": [
"v23.9.0",
"v22.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/56765",
"description": "Add the `options` parameter."
},
{
"version": [
"v23.4.0",
"v22.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/55895",
"description": "This function is no longer experimental."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`count` {number} The number of assertions and subtests that are expected to run.",
"name": "count",
"type": "number",
"desc": "The number of assertions and subtests that are expected to run."
},
{
"textRaw": "`options` {Object} Additional options for the plan.",
"name": "options",
"type": "Object",
"desc": "Additional options for the plan.",
"options": [
{
"textRaw": "`wait` {boolean|number} The wait time for the plan:If `true`, the plan waits indefinitely for all assertions and subtests to run.If `false`, the plan performs an immediate check after the test function completes, without waiting for any pending assertions or subtests. Any assertions or subtests that complete after this check will not be counted towards the plan.If a number, it specifies the maximum wait time in milliseconds before timing out while waiting for expected assertions and subtests to be matched. If the timeout is reached, the test will fail. **Default:** `false`.",
"name": "wait",
"type": "boolean|number",
"default": "`false`",
"desc": "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."
}
],
"optional": true
}
]
}
],
"desc": "This function is used to set the number of assertions and subtests that are expected to run\nwithin the test. If the number of assertions and subtests that run does not match the\nexpected count, the test will fail.
\n\nNote: To make sure assertions are tracked, t.assert must be used instead of assert directly.
\n
\ntest('top level test', (t) => {\n t.plan(2);\n t.assert.ok('some relevant assertion here');\n t.test('subtest', () => {});\n});\n
\nWhen working with asynchronous code, the plan function can be used to ensure that the\ncorrect number of assertions are run:
\ntest('planning with streams', (t, done) => {\n function* generate() {\n yield 'a';\n yield 'b';\n yield 'c';\n }\n const expected = ['a', 'b', 'c'];\n t.plan(expected.length);\n const stream = Readable.from(generate());\n stream.on('data', (chunk) => {\n t.assert.strictEqual(chunk, expected.shift());\n });\n\n stream.on('end', () => {\n done();\n });\n});\n
\nWhen using the wait option, you can control how long the test will wait for the expected assertions.\nFor example, setting a maximum wait time ensures that the test will wait for asynchronous assertions\nto complete within the specified timeframe:
\ntest('plan with wait: 2000 waits for async assertions', (t) => {\n t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete.\n\n const asyncActivity = () => {\n setTimeout(() => {\n t.assert.ok(true, 'Async assertion completed within the wait time');\n }, 1000); // Completes after 1 second, within the 2-second wait time.\n };\n\n asyncActivity(); // The test will pass because the assertion is completed in time.\n});\n
\nNote: If a wait timeout is specified, it begins counting down only after the test function finishes executing.
"
},
{
"textRaw": "`context.runOnly(shouldRunOnlyTests)`",
"name": "runOnly",
"type": "method",
"meta": {
"added": [
"v18.0.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`shouldRunOnlyTests` {boolean} Whether or not to run `only` tests.",
"name": "shouldRunOnlyTests",
"type": "boolean",
"desc": "Whether or not to run `only` tests."
}
]
}
],
"desc": "If shouldRunOnlyTests is truthy, the test context will only run tests that\nhave the only option set. Otherwise, all tests are run. If Node.js was not\nstarted with the --test-only command-line option, this function is a\nno-op.
\ntest('top level test', (t) => {\n // The test context can be set to run subtests with the 'only' option.\n t.runOnly(true);\n return Promise.all([\n t.test('this subtest is now skipped'),\n t.test('this subtest is run', { only: true }),\n ]);\n});\n
"
},
{
"textRaw": "`context.skip([message])`",
"name": "skip",
"type": "method",
"meta": {
"added": [
"v18.0.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`message` {string} Optional skip message.",
"name": "message",
"type": "string",
"desc": "Optional skip message.",
"optional": true
}
]
}
],
"desc": "This function causes the test's output to indicate the test as skipped. If\nmessage is provided, it is included in the output. Calling skip() does\nnot terminate execution of the test function. This function does not return a\nvalue.
\ntest('top level test', (t) => {\n // Make sure to return here as well if the test contains additional logic.\n t.skip('this is skipped');\n});\n
"
},
{
"textRaw": "`context.todo([message])`",
"name": "todo",
"type": "method",
"meta": {
"added": [
"v18.0.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`message` {string} Optional `TODO` message.",
"name": "message",
"type": "string",
"desc": "Optional `TODO` message.",
"optional": true
}
]
}
],
"desc": "This function adds a TODO directive to the test's output. If message is\nprovided, it is included in the output. Calling todo() does not terminate\nexecution of the test function. This function does not return a value.
\ntest('top level test', (t) => {\n // This test is marked as `TODO`\n t.todo('this is a todo');\n});\n
"
},
{
"textRaw": "`context.test([name][, options][, fn])`",
"name": "test",
"type": "method",
"meta": {
"added": [
"v18.0.0",
"v16.17.0"
],
"changes": [
{
"version": [
"v18.8.0",
"v16.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/43554",
"description": "Add a `signal` option."
},
{
"version": [
"v18.7.0",
"v16.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/43505",
"description": "Add a `timeout` option."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} The name of the subtest, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `''` if `fn` does not have a name.",
"name": "name",
"type": "string",
"default": "The `name` property of `fn`, or `''` if `fn` does not have a name",
"desc": "The name of the subtest, which is displayed when reporting test results.",
"optional": true
},
{
"textRaw": "`options` {Object} Configuration options for the subtest. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Configuration options for the subtest. The following properties are supported:",
"options": [
{
"textRaw": "`concurrency` {number|boolean|null} If a number is provided, then that many tests would run asynchronously (they are still managed by the single-threaded event loop). If `true`, it would run all subtests in parallel. If `false`, it would only run one test at a time. If unspecified, subtests inherit this value from their parent. **Default:** `null`.",
"name": "concurrency",
"type": "number|boolean|null",
"default": "`null`",
"desc": "If a number is provided, then that many tests would run asynchronously (they are still managed by the single-threaded event loop). If `true`, it would run all subtests in parallel. If `false`, it would only run one test at a time. If unspecified, subtests inherit this value from their parent."
},
{
"textRaw": "`only` {boolean} If truthy, and the test context is configured to run `only` tests, then this test will be run. Otherwise, the test is skipped. **Default:** `false`.",
"name": "only",
"type": "boolean",
"default": "`false`",
"desc": "If truthy, and the test context is configured to run `only` tests, then this test will be run. Otherwise, the test is skipped."
},
{
"textRaw": "`signal` {AbortSignal} Allows aborting an in-progress test.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows aborting an in-progress test."
},
{
"textRaw": "`skip` {boolean|string} If truthy, the test is skipped. If a string is provided, that string is displayed in the test results as the reason for skipping the test. **Default:** `false`.",
"name": "skip",
"type": "boolean|string",
"default": "`false`",
"desc": "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."
},
{
"textRaw": "`todo` {boolean|string} If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in the test results as the reason why the test is `TODO`. **Default:** `false`.",
"name": "todo",
"type": "boolean|string",
"default": "`false`",
"desc": "If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in the test results as the reason why the test is `TODO`."
},
{
"textRaw": "`timeout` {number} A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. **Default:** `Infinity`.",
"name": "timeout",
"type": "number",
"default": "`Infinity`",
"desc": "A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent."
},
{
"textRaw": "`plan` {number} The number of assertions and subtests expected to be run in the test. If the number of assertions run in the test does not match the number specified in the plan, the test will fail. **Default:** `undefined`.",
"name": "plan",
"type": "number",
"default": "`undefined`",
"desc": "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."
}
],
"optional": true
},
{
"textRaw": "`fn` {Function|AsyncFunction} The function under test. The first argument to this function is a `TestContext` object. If the test uses callbacks, the callback function is passed as the second argument. **Default:** A no-op function.",
"name": "fn",
"type": "Function|AsyncFunction",
"default": "A no-op function",
"desc": "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.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfilled with `undefined` once the test completes.",
"name": "return",
"type": "Promise",
"desc": "Fulfilled with `undefined` once the test completes."
}
}
],
"desc": "This function is used to create subtests under the current test. This function\nbehaves in the same fashion as the top level test() function.
\ntest('top level test', async (t) => {\n await t.test(\n 'This is a subtest',\n { only: false, skip: false, concurrency: 1, todo: false, plan: 1 },\n (t) => {\n t.assert.ok('some relevant assertion here');\n },\n );\n});\n
"
},
{
"textRaw": "`context.waitFor(condition[, options])`",
"name": "waitFor",
"type": "method",
"meta": {
"added": [
"v23.7.0",
"v22.14.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`condition` {Function|AsyncFunction} An assertion function that is invoked periodically until it completes successfully or the defined polling timeout elapses. Successful completion is defined as not throwing or rejecting. This function does not accept any arguments, and is allowed to return any value.",
"name": "condition",
"type": "Function|AsyncFunction",
"desc": "An assertion function that is invoked periodically until it completes successfully or the defined polling timeout elapses. Successful completion is defined as not throwing or rejecting. This function does not accept any arguments, and is allowed to return any value."
},
{
"textRaw": "`options` {Object} An optional configuration object for the polling operation. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "An optional configuration object for the polling operation. The following properties are supported:",
"options": [
{
"textRaw": "`interval` {number} The number of milliseconds to wait after an unsuccessful invocation of `condition` before trying again. **Default:** `50`.",
"name": "interval",
"type": "number",
"default": "`50`",
"desc": "The number of milliseconds to wait after an unsuccessful invocation of `condition` before trying again."
},
{
"textRaw": "`timeout` {number} The poll timeout in milliseconds. If `condition` has not succeeded by the time this elapses, an error occurs. **Default:** `1000`.",
"name": "timeout",
"type": "number",
"default": "`1000`",
"desc": "The poll timeout in milliseconds. If `condition` has not succeeded by the time this elapses, an error occurs."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfilled with the value returned by `condition`.",
"name": "return",
"type": "Promise",
"desc": "Fulfilled with the value returned by `condition`."
}
}
],
"desc": "This method polls a condition function until that function either returns\nsuccessfully or the operation times out.
"
}
],
"properties": [
{
"textRaw": "`context.assert`",
"name": "assert",
"type": "property",
"meta": {
"added": [
"v22.2.0",
"v20.15.0"
],
"changes": []
},
"desc": "An object containing assertion methods bound to context. The top-level\nfunctions from the node:assert module are exposed here for the purpose of\ncreating test plans.
\ntest('test', (t) => {\n t.plan(1);\n t.assert.strictEqual(true, true);\n});\n
",
"methods": [
{
"textRaw": "`context.assert.fileSnapshot(value, path[, options])`",
"name": "fileSnapshot",
"type": "method",
"meta": {
"added": [
"v23.7.0",
"v22.14.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} A value to serialize to a string. If Node.js was started with the `--test-update-snapshots` flag, the serialized value is written to `path`. Otherwise, the serialized value is compared to the contents of the existing snapshot file.",
"name": "value",
"type": "any",
"desc": "A value to serialize to a string. If Node.js was started with the `--test-update-snapshots` flag, the serialized value is written to `path`. Otherwise, the serialized value is compared to the contents of the existing snapshot file."
},
{
"textRaw": "`path` {string} The file where the serialized `value` is written.",
"name": "path",
"type": "string",
"desc": "The file where the serialized `value` is written."
},
{
"textRaw": "`options` {Object} Optional configuration options. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Optional configuration options. The following properties are supported:",
"options": [
{
"textRaw": "`serializers` {Array} An array of synchronous functions used to serialize `value` into a string. `value` is passed as the only argument to the first serializer function. The return value of each serializer is passed as input to the next serializer. Once all serializers have run, the resulting value is coerced to a string. **Default:** If no serializers are provided, the test runner's default serializers are used.",
"name": "serializers",
"type": "Array",
"default": "If no serializers are provided, the test runner's default serializers are used",
"desc": "An array of synchronous functions used to serialize `value` into a string. `value` is passed as the only argument to the first serializer function. The return value of each serializer is passed as input to the next serializer. Once all serializers have run, the resulting value is coerced to a string."
}
],
"optional": true
}
]
}
],
"desc": "This function serializes value and writes it to the file specified by path.
\ntest('snapshot test with default serialization', (t) => {\n t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json');\n});\n
\nThis function differs from context.assert.snapshot() in the following ways:
\n\n- The snapshot file path is explicitly provided by the user.
\n- Each snapshot file is limited to a single snapshot value.
\n- No additional escaping is performed by the test runner.
\n
\nThese differences allow snapshot files to better support features such as syntax\nhighlighting.
"
},
{
"textRaw": "`context.assert.snapshot(value[, options])`",
"name": "snapshot",
"type": "method",
"meta": {
"added": [
"v22.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} A value to serialize to a string. If Node.js was started with the `--test-update-snapshots` flag, the serialized value is written to the snapshot file. Otherwise, the serialized value is compared to the corresponding value in the existing snapshot file.",
"name": "value",
"type": "any",
"desc": "A value to serialize to a string. If Node.js was started with the `--test-update-snapshots` flag, the serialized value is written to the snapshot file. Otherwise, the serialized value is compared to the corresponding value in the existing snapshot file."
},
{
"textRaw": "`options` {Object} Optional configuration options. The following properties are supported:",
"name": "options",
"type": "Object",
"desc": "Optional configuration options. The following properties are supported:",
"options": [
{
"textRaw": "`serializers` {Array} An array of synchronous functions used to serialize `value` into a string. `value` is passed as the only argument to the first serializer function. The return value of each serializer is passed as input to the next serializer. Once all serializers have run, the resulting value is coerced to a string. **Default:** If no serializers are provided, the test runner's default serializers are used.",
"name": "serializers",
"type": "Array",
"default": "If no serializers are provided, the test runner's default serializers are used",
"desc": "An array of synchronous functions used to serialize `value` into a string. `value` is passed as the only argument to the first serializer function. The return value of each serializer is passed as input to the next serializer. Once all serializers have run, the resulting value is coerced to a string."
}
],
"optional": true
}
]
}
],
"desc": "This function implements assertions for snapshot testing.
\ntest('snapshot test with default serialization', (t) => {\n t.assert.snapshot({ value1: 1, value2: 2 });\n});\n\ntest('snapshot test with custom serialization', (t) => {\n t.assert.snapshot({ value3: 3, value4: 4 }, {\n serializers: [(value) => JSON.stringify(value)],\n });\n});\n
"
}
]
},
{
"textRaw": "`context.filePath`",
"name": "filePath",
"type": "property",
"meta": {
"added": [
"v22.6.0",
"v20.16.0"
],
"changes": []
},
"desc": "The absolute path of the test file that created the current test. If a test file\nimports additional modules that generate tests, the imported tests will return\nthe path of the root test file.
"
},
{
"textRaw": "`context.fullName`",
"name": "fullName",
"type": "property",
"meta": {
"added": [
"v22.3.0",
"v20.16.0"
],
"changes": []
},
"desc": "The name of the test and each of its ancestors, separated by >.
"
},
{
"textRaw": "`context.name`",
"name": "name",
"type": "property",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"desc": "The name of the test.
"
},
{
"textRaw": "Type: {boolean} `false` before the test is executed, e.g. in a `beforeEach` hook.",
"name": "passed",
"type": "boolean",
"meta": {
"added": [
"v21.7.0",
"v20.12.0"
],
"changes": []
},
"desc": "Indicated whether the test succeeded.
",
"shortDesc": "`false` before the test is executed, e.g. in a `beforeEach` hook."
},
{
"textRaw": "Type: {Error|null}",
"name": "error",
"type": "Error|null",
"meta": {
"added": [
"v21.7.0",
"v20.12.0"
],
"changes": []
},
"desc": "The failure reason for the test/case; wrapped and available via context.error.cause.
"
},
{
"textRaw": "Type: {number}",
"name": "attempt",
"type": "number",
"meta": {
"added": [
"v25.0.0"
],
"changes": []
},
"desc": "Number of times the test has been attempted.
"
},
{
"textRaw": "Type: {number|undefined}",
"name": "workerId",
"type": "number|undefined",
"meta": {
"added": [
"v25.8.0"
],
"changes": []
},
"desc": "The unique identifier of the worker running the current test file. This value is\nderived from the NODE_TEST_WORKER_ID environment variable. When running tests\nwith --test-isolation=process (the default), each test file runs in a separate\nchild process and is assigned a worker ID from 1 to N, where N is the number of\nconcurrent workers. When running with --test-isolation=none, all tests run in\nthe same process and the worker ID is always 1. This value is undefined when\nnot running in a test context.
\nThis property is useful for splitting resources (like database connections or\nserver ports) across concurrent test files:
\nimport { test } from 'node:test';\nimport { process } from 'node:process';\n\ntest('database operations', async (t) => {\n // Worker ID is available via context\n console.log(`Running in worker ${t.workerId}`);\n\n // Or via environment variable (available at import time)\n const workerId = process.env.NODE_TEST_WORKER_ID;\n // Use workerId to allocate separate resources per worker\n});\n
"
},
{
"textRaw": "Type: {AbortSignal}",
"name": "signal",
"type": "AbortSignal",
"meta": {
"added": [
"v18.7.0",
"v16.17.0"
],
"changes": []
},
"desc": "Can be used to abort test subtasks when the test has been aborted.
\ntest('top level test', async (t) => {\n await fetch('some/uri', { signal: t.signal });\n});\n
"
}
]
},
{
"textRaw": "Class: `SuiteContext`",
"name": "SuiteContext",
"type": "class",
"meta": {
"added": [
"v18.7.0",
"v16.17.0"
],
"changes": []
},
"desc": "An instance of SuiteContext is passed to each suite function in order to\ninteract with the test runner. However, the SuiteContext constructor is not\nexposed as part of the API.
",
"properties": [
{
"textRaw": "`context.filePath`",
"name": "filePath",
"type": "property",
"meta": {
"added": [
"v22.6.0"
],
"changes": []
},
"desc": "The absolute path of the test file that created the current suite. If a test\nfile imports additional modules that generate suites, the imported suites will\nreturn the path of the root test file.
"
},
{
"textRaw": "`context.fullName`",
"name": "fullName",
"type": "property",
"meta": {
"added": [
"v22.3.0",
"v20.16.0"
],
"changes": []
},
"desc": "The name of the suite and each of its ancestors, separated by >.
"
},
{
"textRaw": "`context.name`",
"name": "name",
"type": "property",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"desc": "The name of the suite.
"
},
{
"textRaw": "Type: {AbortSignal}",
"name": "signal",
"type": "AbortSignal",
"meta": {
"added": [
"v18.7.0",
"v16.17.0"
],
"changes": []
},
"desc": "Can be used to abort test subtasks when the test has been aborted.
"
}
]
}
],
"displayName": "Test runner"
}
]
}