{ "type": "module", "source": "doc/api/test.md", "modules": [ { "textRaw": "Test runner", "name": "test_runner", "introduced_in": "v18.0.0", "meta": { "added": [ "v18.0.0", "v16.17.0" ], "changes": [ { "version": "v20.0.0", "pr-url": "https://github.com/nodejs/node/pull/46983", "description": "The test runner is now stable." } ] }, "stability": 2, "stabilityText": "Stable", "desc": "
Source Code: lib/test.js
\nThe node:test
module facilitates the creation of JavaScript tests.\nTo access it:
import test from 'node:test';\n
\nconst test = require('node:test');\n
\nThis module is only available under the node:
scheme. The following will not\nwork:
import test from 'test';\n
\nconst test = require('test');\n
\nTests created via the test
module consist of a single function that is\nprocessed in one of three ways:
Promise
that is considered failing if the\nPromise
rejects, and is considered passing if the Promise
fulfills.Promise
, the test will fail.The following example illustrates how tests are written using the\ntest
module.
test('synchronous passing test', (t) => {\n // This test passes because it does not throw an exception.\n assert.strictEqual(1, 1);\n});\n\ntest('synchronous failing test', (t) => {\n // This test fails because it throws an exception.\n assert.strictEqual(1, 2);\n});\n\ntest('asynchronous passing test', async (t) => {\n // This test passes because the Promise returned by the async\n // function is settled and not rejected.\n assert.strictEqual(1, 1);\n});\n\ntest('asynchronous failing test', async (t) => {\n // This test fails because the Promise returned by the async\n // function is rejected.\n assert.strictEqual(1, 2);\n});\n\ntest('failing test using Promises', (t) => {\n // Promises can be used directly as well.\n return new Promise((resolve, reject) => {\n setImmediate(() => {\n reject(new Error('this will cause the test to fail'));\n });\n });\n});\n\ntest('callback passing test', (t, done) => {\n // done() is the callback function. When the setImmediate() runs, it invokes\n // done() with no arguments.\n setImmediate(done);\n});\n\ntest('callback failing test', (t, done) => {\n // When the setImmediate() runs, done() is invoked with an Error object and\n // the test fails.\n setImmediate(() => {\n done(new Error('callback failure'));\n });\n});\n
\nIf any tests fail, the process exit code is set to 1
.
The test context's test()
method allows subtests to be created.\nIt allows you to structure your tests in a hierarchical manner,\nwhere you can create nested tests within a larger test.\nThis method behaves identically to the top level test()
function.\nThe following example demonstrates the creation of a\ntop level test with two subtests.
test('top level test', async (t) => {\n await t.test('subtest 1', (t) => {\n assert.strictEqual(1, 1);\n });\n\n await t.test('subtest 2', (t) => {\n assert.strictEqual(2, 2);\n });\n});\n
\n\n\nNote:
\nbeforeEach
andafterEach
hooks are triggered\nbetween each subtest execution.
In this example, await
is used to ensure that both subtests have completed.\nThis is necessary because parent tests do not wait for their subtests to\ncomplete, unlike tests created with the describe
and it
syntax.\nAny subtests that are still outstanding when their parent finishes\nare cancelled and treated as failures. Any subtest failures cause the parent\ntest to fail.
Individual tests can be skipped by passing the skip
option to the test, or by\ncalling the test context's skip()
method as shown in the\nfollowing example.
// The skip option is used, but no message is provided.\ntest('skip option', { skip: true }, (t) => {\n // This code is never executed.\n});\n\n// The skip option is used, and a message is provided.\ntest('skip option with message', { skip: 'this is skipped' }, (t) => {\n // This code is never executed.\n});\n\ntest('skip() method', (t) => {\n // Make sure to return here as well if the test contains additional logic.\n t.skip();\n});\n\ntest('skip() method with message', (t) => {\n // Make sure to return here as well if the test contains additional logic.\n t.skip('this is skipped');\n});\n
",
"type": "module",
"displayName": "Skipping tests"
},
{
"textRaw": "`describe`/`it` syntax",
"name": "`describe`/`it`_syntax",
"desc": "Running tests can also be done using describe
to declare a suite\nand it
to declare a test.\nA suite is used to organize and group related tests together.\nit
is a shorthand for test()
.
describe('A thing', () => {\n it('should work', () => {\n assert.strictEqual(1, 1);\n });\n\n it('should be ok', () => {\n assert.strictEqual(2, 2);\n });\n\n describe('a nested thing', () => {\n it('should work', () => {\n assert.strictEqual(3, 3);\n });\n });\n});\n
\ndescribe
and it
are imported from the node:test
module.
import { describe, it } from 'node:test';\n
\nconst { describe, it } = require('node:test');\n
",
"type": "module",
"displayName": "`describe`/`it` syntax"
},
{
"textRaw": "`only` tests",
"name": "`only`_tests",
"desc": "If Node.js is started with the --test-only
command-line option, it is\npossible to skip all top level tests except for a selected subset by passing\nthe only
option to the tests that should be run. When a test with the only
\noption set is run, all subtests are also run. The test context's runOnly()
\nmethod can be used to implement the same behavior at the subtest level.
// Assume Node.js is run with the --test-only command-line option.\n// The 'only' option is set, so this test is run.\ntest('this test is run', { only: true }, async (t) => {\n // Within this test, all subtests are run by default.\n await t.test('running subtest');\n\n // The test context can be updated to run subtests with the 'only' option.\n t.runOnly(true);\n await t.test('this subtest is now skipped');\n await t.test('this subtest is run', { only: true });\n\n // Switch the context back to execute all tests.\n t.runOnly(false);\n await t.test('this subtest is now run');\n\n // Explicitly do not run these tests.\n await t.test('skipped subtest 3', { only: false });\n await t.test('skipped subtest 4', { skip: true });\n});\n\n// The 'only' option is not set, so this test is skipped.\ntest('this test is not run', () => {\n // This code is not run.\n throw new Error('fail');\n});\n
",
"type": "module",
"displayName": "`only` tests"
},
{
"textRaw": "Filtering tests by name",
"name": "filtering_tests_by_name",
"desc": "The --test-name-pattern
command-line option can be used to only run tests\nwhose name matches the provided pattern. Test name patterns are interpreted as\nJavaScript regular expressions. The --test-name-pattern
option can be\nspecified multiple times in order to run nested tests. For each test that is\nexecuted, any corresponding test hooks, such as beforeEach()
, are also\nrun.
Given the following test file, starting Node.js with the\n--test-name-pattern=\"test [1-3]\"
option would cause the test runner to execute\ntest 1
, test 2
, and test 3
. If test 1
did not match the test name\npattern, then its subtests would not execute, despite matching the pattern. The\nsame set of tests could also be executed by passing --test-name-pattern
\nmultiple times (e.g. --test-name-pattern=\"test 1\"
,\n--test-name-pattern=\"test 2\"
, etc.).
test('test 1', async (t) => {\n await t.test('test 2');\n await t.test('test 3');\n});\n\ntest('Test 4', async (t) => {\n await t.test('Test 5');\n await t.test('test 6');\n});\n
\nTest name patterns can also be specified using regular expression literals. This\nallows regular expression flags to be used. In the previous example, starting\nNode.js with --test-name-pattern=\"/test [4-5]/i\"
would match Test 4
and\nTest 5
because the pattern is case-insensitive.
Test name patterns do not change the set of files that the test runner executes.
", "type": "module", "displayName": "Filtering tests by name" }, { "textRaw": "Extraneous asynchronous activity", "name": "extraneous_asynchronous_activity", "desc": "Once a test function finishes executing, the results are reported as quickly\nas possible while maintaining the order of the tests. However, it is possible\nfor the test function to generate asynchronous activity that outlives the test\nitself. The test runner handles this type of activity, but does not delay the\nreporting of test results in order to accommodate it.
\nIn the following example, a test completes with two setImmediate()
\noperations still outstanding. The first setImmediate()
attempts to create a\nnew subtest. Because the parent test has already finished and output its\nresults, the new subtest is immediately marked as failed, and reported later\nto the <TestsStream>.
The second setImmediate()
creates an uncaughtException
event.\nuncaughtException
and unhandledRejection
events originating from a completed\ntest are marked as failed by the test
module and reported as diagnostic\nwarnings at the top level by the <TestsStream>.
test('a test that creates asynchronous activity', (t) => {\n setImmediate(() => {\n t.test('subtest that is created too late', (t) => {\n throw new Error('error1');\n });\n });\n\n setImmediate(() => {\n throw new Error('error2');\n });\n\n // The test finishes after this line.\n});\n
",
"type": "module",
"displayName": "Extraneous asynchronous activity"
},
{
"textRaw": "Watch mode",
"name": "watch_mode",
"meta": {
"added": [
"v19.2.0",
"v18.13.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "The Node.js test runner supports running in watch mode by passing the --watch
flag:
node --test --watch\n
\nIn watch mode, the test runner will watch for changes to test files and\ntheir dependencies. When a change is detected, the test runner will\nrerun the tests affected by the change.\nThe test runner will continue to run until the process is terminated.
", "type": "module", "displayName": "Watch mode" }, { "textRaw": "Running tests from the command line", "name": "running_tests_from_the_command_line", "desc": "The Node.js test runner can be invoked from the command line by passing the\n--test
flag:
node --test\n
\nBy default Node.js will run all files matching these patterns:
\n**/*.test.?(c|m)js
**/*-test.?(c|m)js
**/*_test.?(c|m)js
**/test-*.?(c|m)js
**/test.?(c|m)js
**/test/**/*.?(c|m)js
Alternatively, one or more glob patterns can be provided as the\nfinal argument(s) to the Node.js command, as shown below.\nGlob patterns follow the behavior of glob(7)
.
node --test **/*.test.js **/*.spec.js\n
\nMatching files are executed as test files.\nMore information on the test file execution can be found\nin the test runner execution model section.
", "modules": [ { "textRaw": "Test runner execution model", "name": "test_runner_execution_model", "desc": "Each matching test file is executed in a separate child process. The maximum\nnumber of child processes running at any time is controlled by the\n--test-concurrency
flag. If the child process finishes with an exit code\nof 0, the test is considered passing. Otherwise, the test is considered to be a\nfailure. Test files must be executable by Node.js, but are not required to use\nthe node:test
module internally.
Each test file is executed as if it was a regular script. That is, if the test\nfile itself uses node:test
to define tests, all of those tests will be\nexecuted within a single application thread, regardless of the value of the\nconcurrency
option of test()
.
When Node.js is started with the --experimental-test-coverage
\ncommand-line flag, code coverage is collected and statistics are reported once\nall tests have completed. If the NODE_V8_COVERAGE
environment variable is\nused to specify a code coverage directory, the generated V8 coverage files are\nwritten to that directory. Node.js core modules and files within\nnode_modules/
directories are not included in the coverage report. If\ncoverage is enabled, the coverage report is sent to any test reporters via\nthe 'test:coverage'
event.
Coverage can be disabled on a series of lines using the following\ncomment syntax:
\n/* node:coverage disable */\nif (anAlwaysFalseCondition) {\n // Code in this branch will never be executed, but the lines are ignored for\n // coverage purposes. All lines following the 'disable' comment are ignored\n // until a corresponding 'enable' comment is encountered.\n console.log('this is never executed');\n}\n/* node:coverage enable */\n
\nCoverage can also be disabled for a specified number of lines. After the\nspecified number of lines, coverage will be automatically reenabled. If the\nnumber of lines is not explicitly provided, a single line is ignored.
\n/* node:coverage ignore next */\nif (anAlwaysFalseCondition) { console.log('this is never executed'); }\n\n/* node:coverage ignore next 3 */\nif (anAlwaysFalseCondition) {\n console.log('this is never executed');\n}\n
",
"modules": [
{
"textRaw": "Coverage reporters",
"name": "coverage_reporters",
"desc": "The tap and spec reporters will print a summary of the coverage statistics.\nThere is also an lcov reporter that will generate an lcov file which can be\nused as an in depth coverage report.
\nnode --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info\n
",
"type": "module",
"displayName": "Coverage reporters"
},
{
"textRaw": "Limitations",
"name": "limitations",
"desc": "The test runner's code coverage functionality has the following limitations,\nwhich will be addressed in a future Node.js release:
\nThe node:test
module supports mocking during testing via a top-level mock
\nobject. The following example creates a spy on a function that adds two numbers\ntogether. The spy is then used to assert that the function was called as\nexpected.
import assert from 'node:assert';\nimport { mock, test } from 'node:test';\n\ntest('spies on a function', () => {\n const sum = mock.fn((a, b) => {\n return a + b;\n });\n\n assert.strictEqual(sum.mock.calls.length, 0);\n assert.strictEqual(sum(3, 4), 7);\n assert.strictEqual(sum.mock.calls.length, 1);\n\n const call = sum.mock.calls[0];\n assert.deepStrictEqual(call.arguments, [3, 4]);\n assert.strictEqual(call.result, 7);\n assert.strictEqual(call.error, undefined);\n\n // Reset the globally tracked mocks.\n mock.reset();\n});\n
\n'use strict';\nconst assert = require('node:assert');\nconst { mock, test } = require('node:test');\n\ntest('spies on a function', () => {\n const sum = mock.fn((a, b) => {\n return a + b;\n });\n\n assert.strictEqual(sum.mock.calls.length, 0);\n assert.strictEqual(sum(3, 4), 7);\n assert.strictEqual(sum.mock.calls.length, 1);\n\n const call = sum.mock.calls[0];\n assert.deepStrictEqual(call.arguments, [3, 4]);\n assert.strictEqual(call.result, 7);\n assert.strictEqual(call.error, undefined);\n\n // Reset the globally tracked mocks.\n mock.reset();\n});\n
\nThe same mocking functionality is also exposed on the TestContext
object\nof each test. The following example creates a spy on an object method using the\nAPI exposed on the TestContext
. The benefit of mocking via the test context is\nthat the test runner will automatically restore all mocked functionality once\nthe test finishes.
test('spies on an object method', (t) => {\n const number = {\n value: 5,\n add(a) {\n return this.value + a;\n },\n };\n\n t.mock.method(number, 'add');\n assert.strictEqual(number.add.mock.calls.length, 0);\n assert.strictEqual(number.add(3), 8);\n assert.strictEqual(number.add.mock.calls.length, 1);\n\n const call = number.add.mock.calls[0];\n\n assert.deepStrictEqual(call.arguments, [3]);\n assert.strictEqual(call.result, 8);\n assert.strictEqual(call.target, undefined);\n assert.strictEqual(call.this, number);\n});\n
",
"modules": [
{
"textRaw": "Timers",
"name": "timers",
"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.
Refer to the MockTimers
class for a full list of methods and features.
This allows developers to write more reliable and\npredictable tests for time-dependent functionality.
\nThe example below shows how to mock setTimeout
.\nUsing .enable({ apis: ['setTimeout'] });
\nit will mock the setTimeout
functions in the node:timers and\nnode:timers/promises modules,\nas well as from the Node.js global context.
Note: Destructuring functions such as\nimport { setTimeout } from 'node:timers'
\nis currently not supported by this API.
import assert from 'node:assert';\nimport { mock, test } from 'node:test';\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', () => {\n const fn = mock.fn();\n\n // Optionally choose what to mock\n mock.timers.enable({ apis: ['setTimeout'] });\n setTimeout(fn, 9999);\n assert.strictEqual(fn.mock.callCount(), 0);\n\n // Advance in time\n mock.timers.tick(9999);\n assert.strictEqual(fn.mock.callCount(), 1);\n\n // Reset the globally tracked mocks.\n mock.timers.reset();\n\n // If you call reset mock instance, it will also reset timers instance\n mock.reset();\n});\n
\nconst assert = require('node:assert');\nconst { mock, test } = require('node:test');\n\ntest('mocks setTimeout to be executed synchronously without having to actually wait for it', () => {\n const fn = mock.fn();\n\n // Optionally choose what to mock\n mock.timers.enable({ apis: ['setTimeout'] });\n setTimeout(fn, 9999);\n assert.strictEqual(fn.mock.callCount(), 0);\n\n // Advance in time\n mock.timers.tick(9999);\n assert.strictEqual(fn.mock.callCount(), 1);\n\n // Reset the globally tracked mocks.\n mock.timers.reset();\n\n // If you call reset mock instance, it'll also reset timers instance\n mock.reset();\n});\n
\nThe same mocking functionality is also exposed in the mock property on the TestContext
object\nof each test. The benefit of mocking via the test context is\nthat the test runner will automatically restore all mocked timers\nfunctionality once the test finishes.
import 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 setTimeout(fn, 9999);\n assert.strictEqual(fn.mock.callCount(), 0);\n\n // Advance in time\n context.mock.timers.tick(9999);\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\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout'] });\n setTimeout(fn, 9999);\n assert.strictEqual(fn.mock.callCount(), 0);\n\n // Advance in time\n context.mock.timers.tick(9999);\n assert.strictEqual(fn.mock.callCount(), 1);\n});\n
",
"type": "module",
"displayName": "Timers"
},
{
"textRaw": "Dates",
"name": "dates",
"desc": "The mock timers API also allows the mocking of the Date
object. This is a\nuseful feature for testing time-dependent functionality, or to simulate\ninternal calendar functions such as Date.now()
.
The dates implementation is also part of the MockTimers
class. Refer to it\nfor a full list of methods and features.
Note: Dates and timers are dependent when mocked together. This means that\nif you have both the Date
and setTimeout
mocked, advancing the time will\nalso advance the mocked date as they simulate a single internal clock.
The example below show how to mock the Date
object and obtain the current\nDate.now()
value.
import assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('mocks the Date object', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['Date'] });\n // If not specified, the initial date will be based on 0 in the UNIX epoch\n assert.strictEqual(Date.now(), 0);\n\n // Advance in time will also advance the date\n context.mock.timers.tick(9999);\n assert.strictEqual(Date.now(), 9999);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('mocks the Date object', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['Date'] });\n // If not specified, the initial date will be based on 0 in the UNIX epoch\n assert.strictEqual(Date.now(), 0);\n\n // Advance in time will also advance the date\n context.mock.timers.tick(9999);\n assert.strictEqual(Date.now(), 9999);\n});\n
\nIf there is no initial epoch set, the initial date will be based on 0 in the\nUnix epoch. This is January 1st, 1970, 00:00:00 UTC. You can set an initial date\nby passing a now
property to the .enable()
method. This value will be used\nas the initial date for the mocked Date
object. It can either be a positive\ninteger, or another Date object.
import assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('mocks the Date object with initial time', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['Date'], now: 100 });\n assert.strictEqual(Date.now(), 100);\n\n // Advance in time will also advance the date\n context.mock.timers.tick(200);\n assert.strictEqual(Date.now(), 300);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('mocks the Date object with initial time', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['Date'], now: 100 });\n assert.strictEqual(Date.now(), 100);\n\n // Advance in time will also advance the date\n context.mock.timers.tick(200);\n assert.strictEqual(Date.now(), 300);\n});\n
\nYou can use the .setTime()
method to manually move the mocked date to another\ntime. This method only accepts a positive integer.
Note: This method will execute any mocked timers that are in the past\nfrom the new time.
\nIn the below example we are setting a new time for the mocked date.
\nimport assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('sets the time of a date object', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['Date'], now: 100 });\n assert.strictEqual(Date.now(), 100);\n\n // Advance in time will also advance the date\n context.mock.timers.setTime(1000);\n context.mock.timers.tick(200);\n assert.strictEqual(Date.now(), 1200);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('sets the time of a date object', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['Date'], now: 100 });\n assert.strictEqual(Date.now(), 100);\n\n // Advance in time will also advance the date\n context.mock.timers.setTime(1000);\n context.mock.timers.tick(200);\n assert.strictEqual(Date.now(), 1200);\n});\n
\nIf you have any timer that's set to run in the past, it will be executed as if\nthe .tick()
method has been called. This is useful if you want to test\ntime-dependent functionality that's already in the past.
import assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('runs timers as setTime passes ticks', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const fn = context.mock.fn();\n setTimeout(fn, 1000);\n\n context.mock.timers.setTime(800);\n // Timer is not executed as the time is not yet reached\n assert.strictEqual(fn.mock.callCount(), 0);\n assert.strictEqual(Date.now(), 800);\n\n context.mock.timers.setTime(1200);\n // Timer is executed as the time is now reached\n assert.strictEqual(fn.mock.callCount(), 1);\n assert.strictEqual(Date.now(), 1200);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('runs timers as setTime passes ticks', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const fn = context.mock.fn();\n setTimeout(fn, 1000);\n\n context.mock.timers.setTime(800);\n // Timer is not executed as the time is not yet reached\n assert.strictEqual(fn.mock.callCount(), 0);\n assert.strictEqual(Date.now(), 800);\n\n context.mock.timers.setTime(1200);\n // Timer is executed as the time is now reached\n assert.strictEqual(fn.mock.callCount(), 1);\n assert.strictEqual(Date.now(), 1200);\n});\n
\nUsing .runAll()
will execute all timers that are currently in the queue. This\nwill also advance the mocked date to the time of the last timer that was\nexecuted as if the time has passed.
import assert from 'node:assert';\nimport { test } from 'node:test';\n\ntest('runs timers as setTime passes ticks', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const fn = context.mock.fn();\n setTimeout(fn, 1000);\n setTimeout(fn, 2000);\n setTimeout(fn, 3000);\n\n context.mock.timers.runAll();\n // All timers are executed as the time is now reached\n assert.strictEqual(fn.mock.callCount(), 3);\n assert.strictEqual(Date.now(), 3000);\n});\n
\nconst assert = require('node:assert');\nconst { test } = require('node:test');\n\ntest('runs timers as setTime passes ticks', (context) => {\n // Optionally choose what to mock\n context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });\n const fn = context.mock.fn();\n setTimeout(fn, 1000);\n setTimeout(fn, 2000);\n setTimeout(fn, 3000);\n\n context.mock.timers.runAll();\n // All timers are executed as the time is now reached\n assert.strictEqual(fn.mock.callCount(), 3);\n assert.strictEqual(Date.now(), 3000);\n});\n
",
"type": "module",
"displayName": "Dates"
}
],
"type": "module",
"displayName": "Mocking"
},
{
"textRaw": "Test reporters",
"name": "test_reporters",
"meta": {
"added": [
"v19.6.0",
"v18.15.0"
],
"changes": [
{
"version": [
"v19.9.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/47238",
"description": "Reporters are now exposed at `node:test/reporters`."
}
]
},
"desc": "The node:test
module supports passing --test-reporter
\nflags for the test runner to use a specific reporter.
The following built-reporters are supported:
\ntap
\nThe tap
reporter outputs the test results in the TAP format.
spec
\nThe spec
reporter outputs the test results in a human-readable format.
dot
\nThe dot
reporter outputs the test results in a compact format,\nwhere each passing test is represented by a .
,\nand each failing test is represented by a X
.
junit
\nThe junit reporter outputs test results in a jUnit XML format
lcov
\nThe lcov
reporter outputs test coverage when used with the\n--experimental-test-coverage
flag.
When stdout
is a TTY, the spec
reporter is used by default.\nOtherwise, the tap
reporter is used by default.
The exact output of these reporters is subject to change between versions of\nNode.js, and should not be relied on programmatically. If programmatic access\nto the test runner's output is required, use the events emitted by the\n<TestsStream>.
\nThe reporters are available via the node:test/reporters
module:
import { tap, spec, dot, junit, lcov } from 'node:test/reporters';\n
\nconst { tap, spec, dot, junit, lcov } = require('node:test/reporters');\n
",
"modules": [
{
"textRaw": "Custom reporters",
"name": "custom_reporters",
"desc": "--test-reporter
can be used to specify a path to custom reporter.\nA custom reporter is a module that exports a value\naccepted by stream.compose.\nReporters should transform events emitted by a <TestsStream>
Example of a custom reporter using <stream.Transform>:
\nimport { Transform } from 'node:stream';\n\nconst customReporter = new Transform({\n writableObjectMode: true,\n transform(event, encoding, callback) {\n switch (event.type) {\n case 'test:dequeue':\n callback(null, `test ${event.data.name} dequeued`);\n break;\n case 'test:enqueue':\n callback(null, `test ${event.data.name} enqueued`);\n break;\n case 'test:watch:drained':\n callback(null, 'test watch queue drained');\n break;\n case 'test:start':\n callback(null, `test ${event.data.name} started`);\n break;\n case 'test:pass':\n callback(null, `test ${event.data.name} passed`);\n break;\n case 'test:fail':\n callback(null, `test ${event.data.name} failed`);\n break;\n case 'test:plan':\n callback(null, 'test plan');\n break;\n case 'test:diagnostic':\n case 'test:stderr':\n case 'test:stdout':\n callback(null, event.data.message);\n break;\n case 'test:coverage': {\n const { totalLineCount } = event.data.summary.totals;\n callback(null, `total line count: ${totalLineCount}\\n`);\n break;\n }\n }\n },\n});\n\nexport default customReporter;\n
\nconst { Transform } = require('node:stream');\n\nconst customReporter = new Transform({\n writableObjectMode: true,\n transform(event, encoding, callback) {\n switch (event.type) {\n case 'test:dequeue':\n callback(null, `test ${event.data.name} dequeued`);\n break;\n case 'test:enqueue':\n callback(null, `test ${event.data.name} enqueued`);\n break;\n case 'test:watch:drained':\n callback(null, 'test watch queue drained');\n break;\n case 'test:start':\n callback(null, `test ${event.data.name} started`);\n break;\n case 'test:pass':\n callback(null, `test ${event.data.name} passed`);\n break;\n case 'test:fail':\n callback(null, `test ${event.data.name} failed`);\n break;\n case 'test:plan':\n callback(null, 'test plan');\n break;\n case 'test:diagnostic':\n case 'test:stderr':\n case 'test:stdout':\n callback(null, event.data.message);\n break;\n case 'test:coverage': {\n const { totalLineCount } = event.data.summary.totals;\n callback(null, `total line count: ${totalLineCount}\\n`);\n break;\n }\n }\n },\n});\n\nmodule.exports = customReporter;\n
\nExample of a custom reporter using a generator function:
\nexport default async function * customReporter(source) {\n for await (const event of source) {\n switch (event.type) {\n case 'test:dequeue':\n yield `test ${event.data.name} dequeued`;\n break;\n case 'test:enqueue':\n yield `test ${event.data.name} enqueued`;\n break;\n case 'test:watch:drained':\n yield 'test watch queue drained';\n break;\n case 'test:start':\n yield `test ${event.data.name} started\\n`;\n break;\n case 'test:pass':\n yield `test ${event.data.name} passed\\n`;\n break;\n case 'test:fail':\n yield `test ${event.data.name} failed\\n`;\n break;\n case 'test:plan':\n yield 'test plan';\n break;\n case 'test:diagnostic':\n case 'test:stderr':\n case 'test:stdout':\n yield `${event.data.message}\\n`;\n break;\n case 'test:coverage': {\n const { totalLineCount } = event.data.summary.totals;\n yield `total line count: ${totalLineCount}\\n`;\n break;\n }\n }\n }\n}\n
\nmodule.exports = async function * customReporter(source) {\n for await (const event of source) {\n switch (event.type) {\n case 'test:dequeue':\n yield `test ${event.data.name} dequeued`;\n break;\n case 'test:enqueue':\n yield `test ${event.data.name} enqueued`;\n break;\n case 'test:watch:drained':\n yield 'test watch queue drained';\n break;\n case 'test:start':\n yield `test ${event.data.name} started\\n`;\n break;\n case 'test:pass':\n yield `test ${event.data.name} passed\\n`;\n break;\n case 'test:fail':\n yield `test ${event.data.name} failed\\n`;\n break;\n case 'test:plan':\n yield 'test plan\\n';\n break;\n case 'test:diagnostic':\n case 'test:stderr':\n case 'test:stdout':\n yield `${event.data.message}\\n`;\n break;\n case 'test:coverage': {\n const { totalLineCount } = event.data.summary.totals;\n yield `total line count: ${totalLineCount}\\n`;\n break;\n }\n }\n }\n};\n
\nThe value provided to --test-reporter
should be a string like one used in an\nimport()
in JavaScript code, or a value provided for --import
.
The --test-reporter
flag can be specified multiple times to report test\nresults in several formats. In this situation\nit is required to specify a destination for each reporter\nusing --test-reporter-destination
.\nDestination can be stdout
, stderr
, or a file path.\nReporters and destinations are paired according\nto the order they were specified.
In the following example, the spec
reporter will output to stdout
,\nand the dot
reporter will output to file.txt
:
node --test-reporter=spec --test-reporter=dot --test-reporter-destination=stdout --test-reporter-destination=file.txt\n
\nWhen a single reporter is specified, the destination will default to stdout
,\nunless a destination is explicitly provided.
Note: shard
is used to horizontally parallelize test running across\nmachines or processes, ideal for large-scale executions across varied\nenvironments. It's incompatible with watch
mode, tailored for rapid\ncode iteration by automatically rerunning tests on file changes.
import { tap } from 'node:test/reporters';\nimport { run } from 'node:test';\nimport process from 'node:process';\nimport path from 'node:path';\n\nrun({ files: [path.resolve('./tests/test.js')] })\n .on('test:fail', () => {\n process.exitCode = 1;\n })\n .compose(tap)\n .pipe(process.stdout);\n
\nconst { tap } = require('node:test/reporters');\nconst { run } = require('node:test');\nconst path = require('node:path');\n\nrun({ files: [path.resolve('./tests/test.js')] })\n .on('test:fail', () => {\n process.exitCode = 1;\n })\n .compose(tap)\n .pipe(process.stdout);\n
"
},
{
"textRaw": "`test([name][, options][, fn])`",
"type": "method",
"name": "test",
"meta": {
"added": [
"v18.0.0",
"v16.17.0"
],
"changes": [
{
"version": [
"v20.2.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/47909",
"description": "Added the `skip`, `todo`, and `only` shorthands."
},
{
"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": [
{
"return": {
"textRaw": "Returns: {Promise} Fulfilled with `undefined` once the test completes, or immediately if the test runs within [`describe()`][].",
"name": "return",
"type": "Promise",
"desc": "Fulfilled with `undefined` once the test completes, or immediately if the test runs within [`describe()`][]."
},
"params": [
{
"textRaw": "`name` {string} The name of the test, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `'The test()
function is the value imported from the test
module. Each\ninvocation of this function results in reporting the test to the <TestsStream>.
The 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.
test()
returns a Promise
that fulfills once the test completes.\nif test()
is called within a describe()
block, 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.
test('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.
Shorthand for skipping a test,\nsame as test([name], { skip: true }[, fn])
.
Shorthand for marking a test as TODO
,\nsame as test([name], { todo: true }[, fn])
.
Shorthand for marking a test as only
,\nsame as test([name], { only: true }[, fn])
.
The describe()
function imported from the node:test
module. Each\ninvocation of this function results in the creation of a Subtest.\nAfter invocation of top level describe
functions,\nall top level tests and suites will execute.
Shorthand for skipping a suite, same as describe([name], { skip: true }[, fn])
.
Shorthand for marking a suite as TODO
, same as\ndescribe([name], { todo: true }[, fn])
.
Shorthand for marking a suite as only
, same as\ndescribe([name], { only: true }[, fn])
.
Shorthand for test()
.
The it()
function is imported from the node:test
module.
Shorthand for skipping a test,\nsame as it([name], { skip: true }[, fn])
.
Shorthand for marking a test as TODO
,\nsame as it([name], { todo: true }[, fn])
.
Shorthand for marking a test as only
,\nsame as it([name], { only: true }[, fn])
.
This function is used to create a hook running before running a suite.
\ndescribe('tests', async () => {\n before(() => console.log('about to run some test'));\n it('is a subtest', () => {\n assert.ok('some relevant assertion here');\n });\n});\n
"
},
{
"textRaw": "`after([fn][, options])`",
"type": "method",
"name": "after",
"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."
},
{
"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."
}
]
}
]
}
],
"desc": "This function is used to create a hook running after running a suite.
\ndescribe('tests', async () => {\n after(() => console.log('finished running tests'));\n it('is a subtest', () => {\n assert.ok('some relevant assertion here');\n });\n});\n
\nNote: The after
hook is guaranteed to run,\neven if tests within the suite fail.
This function is used to create a hook running\nbefore each subtest of the current suite.
\ndescribe('tests', async () => {\n beforeEach(() => console.log('about to run a test'));\n it('is a subtest', () => {\n assert.ok('some relevant assertion here');\n });\n});\n
"
},
{
"textRaw": "`afterEach([fn][, options])`",
"type": "method",
"name": "afterEach",
"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."
},
{
"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."
}
]
}
]
}
],
"desc": "This function is used to create a hook running\nafter each subtest of the current test.
\nNote: The afterEach
hook is guaranteed to run after every test,\neven if any of the tests fail.
describe('tests', async () => {\n afterEach(() => console.log('finished running a test'));\n it('is a subtest', () => {\n assert.ok('some relevant assertion here');\n });\n});\n
"
}
],
"classes": [
{
"textRaw": "Class: `MockFunctionContext`",
"type": "class",
"name": "MockFunctionContext",
"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.
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.
\narguments
<Array> An array of the arguments passed to the mock function.error
<any> If the mocked function threw then this property contains the\nthrown value. Default: undefined
.result
<any> The value returned by the mocked function.stack
<Error> An Error
object whose stack can be used to determine the\ncallsite of the mocked function invocation.target
<Function> | <undefined> If the mocked function is a constructor, this\nfield contains the class being constructed. Otherwise this will be\nundefined
.this
<any> The mocked function's this
value.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.
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.
test('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])`",
"type": "method",
"name": "mockImplementationOnce",
"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."
}
]
}
],
"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.
The 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.
test('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()`",
"type": "method",
"name": "resetCalls",
"meta": {
"added": [
"v19.3.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Resets the call history of the mock function.
" }, { "textRaw": "`ctx.restore()`", "type": "method", "name": "restore", "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: `MockTracker`", "type": "class", "name": "MockTracker", "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.
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.
test('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])`",
"type": "method",
"name": "getter",
"meta": {
"added": [
"v19.3.0",
"v18.13.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "This function is syntax sugar for MockTracker.method
with options.getter
\nset to true
.
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.calls.length, 0);\n assert.strictEqual(number.subtract(3), 2);\n assert.strictEqual(number.subtract.mock.calls.length, 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.reset()`",
"type": "method",
"name": "reset",
"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.
After 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.
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.
This function is syntax sugar for MockTracker.method
with options.setter
\nset to true
.
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.
MockTimers is also able to mock the Date
object.
The MockTracker
provides a top-level timers
export\nwhich is a MockTimers
instance.
Enables timer mocking for the specified timers.
\nenableOptions
<Object> Optional configuration options for enabling timer\nmocking. The following properties are supported:\napis
<Array> An optional array containing the timers to mock.\nThe currently supported timer values are 'setInterval'
, 'setTimeout'
, 'setImmediate'
,\nand 'Date'
. Default: ['setInterval', 'setTimeout', 'setImmediate', 'Date']
.\nIf no array is provided, all time related APIs ('setInterval'
, 'clearInterval'
,\n'setTimeout'
, 'clearTimeout'
, and 'Date'
) will be mocked by default.now
<number> | <Date> An optional number or Date object representing the\ninitial time (in milliseconds) to use as the value\nfor Date.now()
. Default: 0
.Note: 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.
Example 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.
Example 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:
All timers ('setInterval'
, 'clearInterval'
, 'setTimeout'
, and 'clearTimeout'
)\nwill be mocked. The setInterval
, clearInterval
, setTimeout
, and clearTimeout
\nfunctions from node:timers
, node:timers/promises
,\nand globalThis
will be mocked. As well as the global Date
object.
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.
Note: After each test completes, this function is called on\nthe test context's MockTracker
.
import { mock } from 'node:test';\nmock.timers.reset();\n
\nconst { mock } = require('node:test');\nmock.timers.reset();\n
"
},
{
"textRaw": "`timers[Symbol.dispose]()`",
"type": "method",
"name": "[Symbol.dispose]",
"signatures": [
{
"params": []
}
],
"desc": "Calls timers.reset()
.
Advances time for all mocked timers.
\nmilliseconds
<number> The amount of time, in milliseconds,\nto advance the timers.Note: 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.
The following example mocks a setTimeout
function and\nby using .tick
advances in\ntime triggering all pending timers.
import 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
\nAlternativelly, the .tick
function can be called many times
import 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 twoSeconds = 3000;\n context.mock.timers.tick(twoSeconds);\n context.mock.timers.tick(twoSeconds);\n context.mock.timers.tick(twoSeconds);\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 twoSeconds = 3000;\n context.mock.timers.tick(twoSeconds);\n context.mock.timers.tick(twoSeconds);\n context.mock.timers.tick(twoSeconds);\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).
import 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",
"desc": "As mentioned, all clear functions from timers (clearTimeout
and clearInterval
)\nare implicity mocked. Take a look at this example using setTimeout
:
import 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 // Implicity 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 // Implicity 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
",
"type": "module",
"displayName": "Using clear functions"
},
{
"textRaw": "Working with Node.js timers modules",
"name": "working_with_node.js_timers_modules",
"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.
import 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:
import 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
",
"type": "module",
"displayName": "Working with Node.js timers modules"
}
]
},
{
"textRaw": "`timers.runAll()`",
"type": "method",
"name": "runAll",
"meta": {
"added": [
"v20.4.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.
The 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.
Sets the current Unix timestamp that will be used as reference for any mocked\nDate
objects.
import 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",
"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.
However, the tick
method will advanced the mocked Date
object.
import 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
",
"type": "module",
"displayName": "Dates and Timers working together"
}
]
}
]
},
{
"textRaw": "Class: `TestsStream`",
"type": "class",
"name": "TestsStream",
"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": "A successful call to run()
method will return a new <TestsStream>\nobject, streaming a series of events representing the execution of the tests.\nTestsStream
will emit events, in the order of the tests definition
Emitted when code coverage is enabled and all tests have completed.
" }, { "textRaw": "Event: `'test:dequeue'`", "type": "event", "name": "test:dequeue", "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 is dequeued, right before it is executed.
" }, { "textRaw": "Event: `'test:diagnostic'`", "type": "event", "name": "test:diagnostic", "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." } ] } ], "desc": "Emitted when context.diagnostic
is called.
Emitted when a test is enqueued for execution.
" }, { "textRaw": "Event: `'test:fail'`", "type": "event", "name": "test:fail", "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": "`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.
" }, { "textRaw": "Event: `'test:pass'`", "type": "event", "name": "test:pass", "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": "`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.
" }, { "textRaw": "Event: `'test:plan'`", "type": "event", "name": "test:plan", "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.
" }, { "textRaw": "Event: `'test:start'`", "type": "event", "name": "test:start", "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.
" }, { "textRaw": "Event: `'test:stderr'`", "type": "event", "name": "test:stderr", "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} The path of the test file.", "name": "file", "type": "string", "desc": "The path of the test file." }, { "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 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.
Emitted when a running test writes to stdout
.\nThis event is only emitted if --test
flag is passed.
Emitted when no more tests are queued for execution in watch mode.
" } ] }, { "textRaw": "Class: `TestContext`", "type": "class", "name": "TestContext", "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.
This function is used to create a hook running before\nsubtest of the current test.
" }, { "textRaw": "`context.beforeEach([fn][, options])`", "type": "method", "name": "beforeEach", "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." }, { "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." } ] } ] } ], "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 assert.ok('some relevant assertion here');\n },\n );\n});\n
"
},
{
"textRaw": "`context.after([fn][, options])`",
"type": "method",
"name": "after",
"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."
},
{
"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."
}
]
}
]
}
],
"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 assert.ok('some relevant assertion here');\n});\n
"
},
{
"textRaw": "`context.afterEach([fn][, options])`",
"type": "method",
"name": "afterEach",
"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."
},
{
"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."
}
]
}
]
}
],
"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 assert.ok('some relevant assertion here');\n },\n );\n});\n
"
},
{
"textRaw": "`context.diagnostic(message)`",
"type": "method",
"name": "diagnostic",
"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.runOnly(shouldRunOnlyTests)`",
"type": "method",
"name": "runOnly",
"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.
test('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])`",
"type": "method",
"name": "skip",
"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."
}
]
}
],
"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.
test('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])`",
"type": "method",
"name": "todo",
"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."
}
]
}
],
"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.
test('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])`",
"type": "method",
"name": "test",
"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": [
{
"return": {
"textRaw": "Returns: {Promise} Fulfilled with `undefined` once the test completes.",
"name": "return",
"type": "Promise",
"desc": "Fulfilled with `undefined` once the test completes."
},
"params": [
{
"textRaw": "`name` {string} The name of the subtest, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `'This function is used to create subtests under the current test. This function\nbehaves in the same fashion as the top level test()
function.
test('top level test', async (t) => {\n await t.test(\n 'This is a subtest',\n { only: false, skip: false, concurrency: 1, todo: false },\n (t) => {\n assert.ok('some relevant assertion here');\n },\n );\n});\n
"
}
],
"properties": [
{
"textRaw": "`context.name`",
"name": "name",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"desc": "The name of the test.
" }, { "textRaw": "`signal` Type: {AbortSignal}", "type": "AbortSignal", "name": "Type", "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`",
"type": "class",
"name": "SuiteContext",
"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.
The name of the suite.
" }, { "textRaw": "`signal` Type: {AbortSignal}", "type": "AbortSignal", "name": "Type", "meta": { "added": [ "v18.7.0", "v16.17.0" ], "changes": [] }, "desc": "Can be used to abort test subtasks when the test has been aborted.
" } ] } ], "type": "module", "displayName": "Test runner" } ] }