{ "type": "module", "source": "doc/api/test.md", "modules": [ { "textRaw": "Test runner", "name": "test_runner", "introduced_in": "v18.0.0", "stability": 1, "stabilityText": "Experimental", "desc": "

Source Code: lib/test.js

\n

The node:test module facilitates the creation of JavaScript tests that\nreport results in TAP format. To access it:

\n
import test from 'node:test';\n
\n
const test = require('node:test');\n
\n

This module is only available under the node: scheme. The following will not\nwork:

\n
import test from 'test';\n
\n
const test = require('test');\n
\n

Tests created via the test module consist of a single function that is\nprocessed in one of three ways:

\n
    \n
  1. A synchronous function that is considered failing if it throws an exception,\nand is considered passing otherwise.
  2. \n
  3. A function that returns a Promise that is considered failing if the\nPromise rejects, and is considered passing if the Promise resolves.
  4. \n
  5. A function that receives a callback function. If the callback receives any\ntruthy value as its first argument, the test is considered failing. If a\nfalsy value is passed as the first argument to the callback, the test is\nconsidered passing. If the test function receives a callback function and\nalso returns a Promise, the test will fail.
  6. \n
\n

The following example illustrates how tests are written using the\ntest module.

\n
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 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
\n

As a test file executes, TAP is written to the standard output of the Node.js\nprocess. This output can be interpreted by any test harness that understands\nthe TAP format. If any tests fail, the process exit code is set to 1.

", "modules": [ { "textRaw": "Subtests", "name": "subtests", "desc": "

The test context's test() method allows subtests to be created. This method\nbehaves identically to the top level test() function. The following example\ndemonstrates the creation of a top level test with two subtests.

\n
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

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. Any subtests that are still outstanding when their parent finishes\nare cancelled and treated as failures. Any subtest failures cause the parent\ntest to fail.

", "type": "module", "displayName": "Subtests" }, { "textRaw": "Skipping tests", "name": "skipping_tests", "desc": "

Individual tests can be skipped by passing the skip option to the test, or by\ncalling the test context's skip() method. Both of these options support\nincluding a message that is displayed in the TAP output as shown in the\nfollowing example.

\n
// 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 an alias for test, except there is no test context passed,\nsince nesting is done using suites.

\n
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
\n

describe and it are imported from the node:test module.

\n
import { describe, it } from 'node:test';\n
\n
const { 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.

\n
// 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.

\n

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.).

\n
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
\n

Test 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.

\n

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 TAP results are output 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.

\n

In 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 in the\ntop level of the file's TAP output.

\n

The second setImmediate() creates an uncaughtException event.\nuncaughtException and unhandledRejection events originating from a completed\ntest are handled by the test module and reported as diagnostic warnings in\nthe top level of the file's TAP output.

\n
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": [ "v18.13.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

The Node.js test runner supports running in watch mode by passing the --watch flag:

\n
node --test --watch\n
\n

In 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:

\n
node --test\n
\n

By default, Node.js will recursively search the current directory for\nJavaScript source files matching a specific naming convention. Matching files\nare executed as test files. More information on the expected test file naming\nconvention and behavior can be found in the test runner execution model\nsection.

\n

Alternatively, one or more paths can be provided as the final argument(s) to\nthe Node.js command, as shown below.

\n
node --test test1.js test2.mjs custom_test_dir/\n
\n

In this example, the test runner will execute the files test1.js and\ntest2.mjs. The test runner will also recursively search the\ncustom_test_dir/ directory for test files to execute.

", "modules": [ { "textRaw": "Test runner execution model", "name": "test_runner_execution_model", "desc": "

When searching for test files to execute, the test runner behaves as follows:

\n\n

Each matching test file is executed in a separate child process. If the child\nprocess finishes with an exit code of 0, the test is considered passing.\nOtherwise, the test is considered to be a failure. Test files must be\nexecutable by Node.js, but are not required to use the node:test module\ninternally.

", "type": "module", "displayName": "Test runner execution model" } ], "type": "module", "displayName": "Running tests from the command line" }, { "textRaw": "Mocking", "name": "mocking", "desc": "

The 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.

\n
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
\n

The 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.

\n
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
", "type": "module", "displayName": "Mocking" } ], "methods": [ { "textRaw": "`run([options])`", "type": "method", "name": "run", "meta": { "added": [ "v18.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {TapStream}", "name": "return", "type": "TapStream" }, "params": [ { "textRaw": "`options` {Object} Configuration options for running tests. The following properties are supported:", "name": "options", "type": "Object", "desc": "Configuration options for running tests. The following properties are supported:", "options": [ { "textRaw": "`concurrency` {number|boolean} If a number is provided, then that many files would run in parallel. If truthy, it would run (number of cpu cores - 1) files in parallel. If falsy, it would only run one file at a time. If unspecified, subtests inherit this value from their parent. **Default:** `true`.", "name": "concurrency", "type": "number|boolean", "default": "`true`", "desc": "If a number is provided, then that many files would run in parallel. If truthy, it would run (number of cpu cores - 1) files in parallel. If falsy, it would only run one file at a time. If unspecified, subtests inherit this value from their parent." }, { "textRaw": "`files`: {Array} An array containing the list of files to run. **Default** matching files from [test runner execution model][].", "name": "files", "type": "Array", "desc": "An array containing the list of files to run. **Default** matching files from [test runner execution model][]." }, { "textRaw": "`signal` {AbortSignal} Allows aborting an in-progress test execution.", "name": "signal", "type": "AbortSignal", "desc": "Allows aborting an in-progress test execution." }, { "textRaw": "`timeout` {number} A number of milliseconds the test execution 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 execution will fail after. If unspecified, subtests inherit this value from their parent." }, { "textRaw": "`inspectPort` {number|Function} Sets inspector port of test child process. This can be a number, or a function that takes no arguments and returns a number. If a nullish value is provided, each process gets its own port, incremented from the primary's `process.debugPort`. **Default:** `undefined`.", "name": "inspectPort", "type": "number|Function", "default": "`undefined`", "desc": "Sets inspector port of test child process. This can be a number, or a function that takes no arguments and returns a number. If a nullish value is provided, each process gets its own port, incremented from the primary's `process.debugPort`." } ] } ] } ], "desc": "
run({ files: [path.resolve('./tests/test.js')] })\n  .pipe(process.stdout);\n
" }, { "textRaw": "`test([name][, options][, fn])`", "type": "method", "name": "test", "meta": { "added": [ "v18.0.0" ], "changes": [ { "version": "v18.8.0", "pr-url": "https://github.com/nodejs/node/pull/43554", "description": "Add a `signal` option." }, { "version": "v18.7.0", "pr-url": "https://github.com/nodejs/node/pull/43505", "description": "Add a `timeout` option." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Resolved with `undefined` once the test completes.", "name": "return", "type": "Promise", "desc": "Resolved with `undefined` once the test completes." }, "params": [ { "textRaw": "`name` {string} The name of the test, 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 test, which is displayed when reporting test results." }, { "textRaw": "`options` {Object} Configuration options for the test. The following properties are supported:", "name": "options", "type": "Object", "desc": "Configuration options for the test. The following properties are supported:", "options": [ { "textRaw": "`concurrency` {number|boolean} If a number is provided, then that many tests would run in parallel. If truthy, it would run (number of cpu cores - 1) tests in parallel. For subtests, it will be `Infinity` tests in parallel. If falsy, it would only run one test at a time. If unspecified, subtests inherit this value from their parent. **Default:** `false`.", "name": "concurrency", "type": "number|boolean", "default": "`false`", "desc": "If a number is provided, then that many tests would run in parallel. If truthy, it would run (number of cpu cores - 1) tests in parallel. For subtests, it will be `Infinity` tests in parallel. If falsy, it would only run one test at a time. If unspecified, subtests inherit this value from their parent." }, { "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": "`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." } ] } ], "desc": "

The test() function is the value imported from the test module. Each\ninvocation of this function results in the creation of a test point in the TAP\noutput.

\n

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 TAP diagnostic information, or creating subtests.

\n

test() returns a Promise that resolves once the test completes. The return\nvalue can usually be discarded for top level tests. However, the return value\nfrom subtests should be used to prevent the parent test from finishing first\nand cancelling the subtest as shown in the following example.

\n
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
\n

The 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": "`describe([name][, options][, fn])`", "type": "method", "name": "describe", "signatures": [ { "return": { "textRaw": "Returns: `undefined`.", "name": "return", "desc": "`undefined`." }, "params": [ { "textRaw": "`name` {string} The name of the suite, 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 suite, which is displayed when reporting test results." }, { "textRaw": "`options` {Object} Configuration options for the suite. supports the same options as `test([name][, options][, fn])`.", "name": "options", "type": "Object", "desc": "Configuration options for the suite. supports the same options as `test([name][, options][, fn])`." }, { "textRaw": "`fn` {Function|AsyncFunction} The function under suite declaring all subtests and subsuites. The first argument to this function is a [`SuiteContext`][] object. **Default:** A no-op function.", "name": "fn", "type": "Function|AsyncFunction", "default": "A no-op function", "desc": "The function under suite declaring all subtests and subsuites. The first argument to this function is a [`SuiteContext`][] object." } ] } ], "desc": "

The describe() function imported from the node:test module. Each\ninvocation of this function results in the creation of a Subtest\nand a test point in the TAP output.\nAfter invocation of top level describe functions,\nall top level tests and suites will execute.

" }, { "textRaw": "`describe.skip([name][, options][, fn])`", "type": "method", "name": "skip", "signatures": [ { "params": [] } ], "desc": "

Shorthand for skipping a suite, same as describe([name], { skip: true }[, fn]).

" }, { "textRaw": "`describe.todo([name][, options][, fn])`", "type": "method", "name": "todo", "signatures": [ { "params": [] } ], "desc": "

Shorthand for marking a suite as TODO, same as\ndescribe([name], { todo: true }[, fn]).

" }, { "textRaw": "`it([name][, options][, fn])`", "type": "method", "name": "it", "signatures": [ { "return": { "textRaw": "Returns: `undefined`.", "name": "return", "desc": "`undefined`." }, "params": [ { "textRaw": "`name` {string} The name of the test, 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 test, which is displayed when reporting test results." }, { "textRaw": "`options` {Object} Configuration options for the suite. supports the same options as `test([name][, options][, fn])`.", "name": "options", "type": "Object", "desc": "Configuration options for the suite. supports the same options as `test([name][, options][, fn])`." }, { "textRaw": "`fn` {Function|AsyncFunction} The function under test. If the test uses callbacks, the callback function is passed as an argument. **Default:** A no-op function.", "name": "fn", "type": "Function|AsyncFunction", "default": "A no-op function", "desc": "The function under test. If the test uses callbacks, the callback function is passed as an argument." } ] } ], "desc": "

The it() function is the value imported from the node:test module.\nEach invocation of this function results in the creation of a test point in the\nTAP output.

" }, { "textRaw": "`it.skip([name][, options][, fn])`", "type": "method", "name": "skip", "signatures": [ { "params": [] } ], "desc": "

Shorthand for skipping a test,\nsame as it([name], { skip: true }[, fn]).

" }, { "textRaw": "`it.todo([name][, options][, fn])`", "type": "method", "name": "todo", "signatures": [ { "params": [] } ], "desc": "

Shorthand for marking a test as TODO,\nsame as it([name], { todo: true }[, fn]).

" }, { "textRaw": "`before([fn][, options])`", "type": "method", "name": "before", "meta": { "added": [ "v18.8.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 before running a suite.

\n
describe('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" ], "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.

\n
describe('tests', async () => {\n  after(() => console.log('finished running tests'));\n  it('is a subtest', () => {\n    assert.ok('some relevant assertion here');\n  });\n});\n
" }, { "textRaw": "`beforeEach([fn][, options])`", "type": "method", "name": "beforeEach", "meta": { "added": [ "v18.8.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\nbefore each subtest of the current suite.

\n
describe('tests', async () => {\n  beforeEach(() => t.diagnostic('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" ], "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.

\n
describe('tests', async () => {\n  afterEach(() => t.diagnostic('about to run 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": [ "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": "`calls` {Array}", "type": "Array", "name": "calls", "meta": { "added": [ "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
    \n
  • arguments <Array> An array of the arguments passed to the mock function.
  • \n
  • error <any> If the mocked function threw then this property contains the\nthrown value. Default: undefined.
  • \n
  • result <any> The value returned by the mocked function.
  • \n
  • stack <Error> An Error object whose stack can be used to determine the\ncallsite of the mocked function invocation.
  • \n
  • target <Function> | <undefined> If the mocked function is a constructor, this\nfield contains the class being constructed. Otherwise this will be\nundefined.
  • \n
  • this <any> The mocked function's this value.
  • \n
" } ], "methods": [ { "textRaw": "`ctx.callCount()`", "type": "method", "name": "callCount", "meta": { "added": [ "v18.13.0" ], "changes": [] }, "signatures": [ { "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." }, "params": [] } ], "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)`", "type": "method", "name": "mockImplementation", "meta": { "added": [ "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.

\n

The following example creates a mock function using t.mock.fn(), calls the\nmock function, and then changes the mock implementation to a different function.

\n
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": [ "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.

\n

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.

\n
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": [ "v18.13.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Resets the call history of the mock function.

" }, { "textRaw": "`ctx.restore()`", "type": "method", "name": "restore", "meta": { "added": [ "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": [ "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])`", "type": "method", "name": "fn", "meta": { "added": [ "v18.13.0" ], "changes": [] }, "signatures": [ { "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." }, "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." }, { "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`." }, { "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." } ] } ] } ], "desc": "

This function is used to create a mock function.

\n

The 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.

\n
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": [ "v18.13.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This function is syntax sugar for MockTracker.method with options.getter\nset to true.

" }, { "textRaw": "`mock.method(object, methodName[, implementation][, options])`", "type": "method", "name": "method", "meta": { "added": [ "v18.13.0" ], "changes": [] }, "signatures": [ { "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." }, "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]`." }, { "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." } ] } ] } ], "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.

\n
test('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": [ "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.

\n

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.

" }, { "textRaw": "`mock.restoreAll()`", "type": "method", "name": "restoreAll", "meta": { "added": [ "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])`", "type": "method", "name": "setter", "meta": { "added": [ "v18.13.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This function is syntax sugar for MockTracker.method with options.setter\nset to true.

" } ] }, { "textRaw": "Class: `TapStream`", "type": "class", "name": "TapStream", "meta": { "added": [ "v18.9.0" ], "changes": [] }, "desc": "\n

A successful call to run() method will return a new <TapStream>\nobject, streaming a TAP output\nTapStream will emit events, in the order of the tests definition

", "events": [ { "textRaw": "Event: `'test:diagnostic'`", "type": "event", "name": "test:diagnostic", "params": [ { "textRaw": "`message` {string} The diagnostic message.", "name": "message", "type": "string", "desc": "The diagnostic message." } ], "desc": "

Emitted when context.diagnostic is called.

" }, { "textRaw": "Event: `'test:fail'`", "type": "event", "name": "test:fail", "params": [ { "textRaw": "`data` {Object}", "name": "data", "type": "Object", "options": [ { "textRaw": "`details` {Object} Additional execution metadata.", "name": "details", "type": "Object", "desc": "Additional execution metadata." }, { "textRaw": "`name` {string} The test name.", "name": "name", "type": "string", "desc": "The test name." }, { "textRaw": "`testNumber` {number} The ordinal number of the test.", "name": "testNumber", "type": "number", "desc": "The ordinal number of the test." }, { "textRaw": "`todo` {string|undefined} Present if [`context.todo`][] is called", "name": "todo", "type": "string|undefined", "desc": "Present if [`context.todo`][] is called" }, { "textRaw": "`skip` {string|undefined} Present if [`context.skip`][] is called", "name": "skip", "type": "string|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": "`details` {Object} Additional execution metadata.", "name": "details", "type": "Object", "desc": "Additional execution metadata." }, { "textRaw": "`name` {string} The test name.", "name": "name", "type": "string", "desc": "The test name." }, { "textRaw": "`testNumber` {number} The ordinal number of the test.", "name": "testNumber", "type": "number", "desc": "The ordinal number of the test." }, { "textRaw": "`todo` {string|undefined} Present if [`context.todo`][] is called", "name": "todo", "type": "string|undefined", "desc": "Present if [`context.todo`][] is called" }, { "textRaw": "`skip` {string|undefined} Present if [`context.skip`][] is called", "name": "skip", "type": "string|undefined", "desc": "Present if [`context.skip`][] is called" } ] } ], "desc": "

Emitted when a test passes.

" } ] }, { "textRaw": "Class: `TestContext`", "type": "class", "name": "TestContext", "meta": { "added": [ "v18.0.0" ], "changes": [] }, "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.beforeEach([fn][, options])`", "type": "method", "name": "beforeEach", "meta": { "added": [ "v18.8.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.

\n
test('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": [ "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.

\n
test('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" ], "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.

\n
test('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" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`message` {string} Message to be displayed as a TAP diagnostic.", "name": "message", "type": "string", "desc": "Message to be displayed as a TAP diagnostic." } ] } ], "desc": "

This function is used to write TAP diagnostics to the output. Any diagnostic\ninformation is included at the end of the test's results. This function does\nnot return a value.

\n
test('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" ], "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.

\n
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" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`message` {string} Optional skip message to be displayed in TAP output.", "name": "message", "type": "string", "desc": "Optional skip message to be displayed in TAP output." } ] } ], "desc": "

This function causes the test's output to indicate the test as skipped. If\nmessage is provided, it is included in the TAP output. Calling skip() does\nnot terminate execution of the test function. This function does not return a\nvalue.

\n
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" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`message` {string} Optional `TODO` message to be displayed in TAP output.", "name": "message", "type": "string", "desc": "Optional `TODO` message to be displayed in TAP output." } ] } ], "desc": "

This function adds a TODO directive to the test's output. If message is\nprovided, it is included in the TAP output. Calling todo() does not terminate\nexecution of the test function. This function does not return a value.

\n
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" ], "changes": [ { "version": "v18.8.0", "pr-url": "https://github.com/nodejs/node/pull/43554", "description": "Add a `signal` option." }, { "version": "v18.7.0", "pr-url": "https://github.com/nodejs/node/pull/43505", "description": "Add a `timeout` option." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Resolved with `undefined` once the test completes.", "name": "return", "type": "Promise", "desc": "Resolved 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 `''` 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." }, { "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} The number of tests that can be run at the same time. If unspecified, subtests inherit this value from their parent. **Default:** `1`.", "name": "concurrency", "type": "number", "default": "`1`", "desc": "The number of tests that can be run at the same 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": "`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." } ] } ], "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.

\n
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" ], "changes": [] }, "desc": "

The name of the test.

" }, { "textRaw": "`signal` {AbortSignal} Can be used to abort test subtasks when the test has been aborted.", "type": "AbortSignal", "name": "signal", "meta": { "added": [ "v18.7.0" ], "changes": [] }, "desc": "
test('top level test', async (t) => {\n  await fetch('some/uri', { signal: t.signal });\n});\n
", "shortDesc": "Can be used to abort test subtasks when the test has been aborted." } ] }, { "textRaw": "Class: `SuiteContext`", "type": "class", "name": "SuiteContext", "meta": { "added": [ "v18.7.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.name`", "name": "name", "meta": { "added": [ "v18.8.0" ], "changes": [] }, "desc": "

The name of the suite.

" }, { "textRaw": "`signal` {AbortSignal} Can be used to abort test subtasks when the test has been aborted.", "type": "AbortSignal", "name": "signal", "meta": { "added": [ "v18.7.0" ], "changes": [] }, "shortDesc": "Can be used to abort test subtasks when the test has been aborted." } ] } ], "type": "module", "displayName": "Test runner" } ] }