home / documentation / v19 / test

Test runner

目录

Added in: v18.0.0

稳定性: 1 - Experimental

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

MJS
CJS

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

MJS
CJS

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

  1. A synchronous function that is considered failing if it throws an exception, and is considered passing otherwise.
  2. A function that returns a Promise that is considered failing if the Promise rejects, and is considered passing if the Promise resolves.
  3. A function that receives a callback function. If the callback receives any truthy value as its first argument, the test is considered failing. If a falsy value is passed as the first argument to the callback, the test is considered passing. If the test function receives a callback function and also returns a Promise, the test will fail.

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

JS

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

Subtests

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

JS

In this example, await is used to ensure that both subtests have completed. This is necessary because parent tests do not wait for their subtests to complete. Any subtests that are still outstanding when their parent finishes are cancelled and treated as failures. Any subtest failures cause the parent test to fail.

Skipping tests

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

JS

M describe/it syntax

Running tests can also be done using describe to declare a suite and it to declare a test. A suite is used to organize and group related tests together. it is an alias for test, except there is no test context passed, since nesting is done using suites.

JS

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

MJS
CJS

M only tests

If Node.js is started with the --test-only command-line option, it is possible to skip all top level tests except for a selected subset by passing the only option to the tests that should be run. When a test with the only option set is run, all subtests are also run. The test context's runOnly() method can be used to implement the same behavior at the subtest level.

JS

Filtering tests by name

The --test-name-pattern command-line option can be used to only run tests whose name matches the provided pattern. Test name patterns are interpreted as JavaScript regular expressions. The --test-name-pattern option can be specified multiple times in order to run nested tests. For each test that is executed, any corresponding test hooks, such as beforeEach(), are also run.

Given the following test file, starting Node.js with the --test-name-pattern="test [1-3]" option would cause the test runner to execute test 1, test 2, and test 3. If test 1 did not match the test name pattern, then its subtests would not execute, despite matching the pattern. The same set of tests could also be executed by passing --test-name-pattern multiple times (e.g. --test-name-pattern="test 1", --test-name-pattern="test 2", etc.).

JS

Test name patterns can also be specified using regular expression literals. This allows regular expression flags to be used. In the previous example, starting Node.js with --test-name-pattern="/test [4-5]/i" would match Test 4 and Test 5 because the pattern is case-insensitive.

Test name patterns do not change the set of files that the test runner executes.

Extraneous asynchronous activity

Once a test function finishes executing, the TAP results are output as quickly as possible while maintaining the order of the tests. However, it is possible for the test function to generate asynchronous activity that outlives the test itself. The test runner handles this type of activity, but does not delay the reporting of test results in order to accommodate it.

In the following example, a test completes with two setImmediate() operations still outstanding. The first setImmediate() attempts to create a new subtest. Because the parent test has already finished and output its results, the new subtest is immediately marked as failed, and reported in the top level of the file's TAP output.

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

JS

Running tests from the command line

The Node.js test runner can be invoked from the command line by passing the --test flag:

BASH

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

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

BASH

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

Test runner execution model

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

  • Any files explicitly provided by the user are executed.
  • If the user did not explicitly specify any paths, the current working directory is recursively searched for files as specified in the following steps.
  • node_modules directories are skipped unless explicitly provided by the user.
  • If a directory named test is encountered, the test runner will search it recursively for all all .js, .cjs, and .mjs files. All of these files are treated as test files, and do not need to match the specific naming convention detailed below. This is to accommodate projects that place all of their tests in a single test directory.
  • In all other directories, .js, .cjs, and .mjs files matching the following patterns are treated as test files:
    • ^test$ - Files whose basename is the string 'test'. Examples: test.js, test.cjs, test.mjs.
    • ^test-.+ - Files whose basename starts with the string 'test-' followed by one or more characters. Examples: test-example.js, test-another-example.mjs.
    • .+[\.\-\_]test$ - Files whose basename ends with .test, -test, or _test, preceded by one or more characters. Examples: example.test.js, example-test.cjs, example_test.mjs.
    • Other file types understood by Node.js such as .node and .json are not automatically executed by the test runner, but are supported if explicitly provided on the command line.

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

Mocking

The node:test module supports mocking during testing via a top-level mock object. The following example creates a spy on a function that adds two numbers together. The spy is then used to assert that the function was called as expected.

MJS
CJS

The same mocking functionality is also exposed on the TestContext object of each test. The following example creates a spy on an object method using the API exposed on the TestContext. The benefit of mocking via the test context is that the test runner will automatically restore all mocked functionality once the test finishes.

JS

M run([options])

Added in: v18.9.0

  • options Object Configuration options for running tests. The following properties are supported:
    • 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.
    • files: Array An array containing the list of files to run. Default matching files from test runner execution model.
    • signal AbortSignal Allows aborting an in-progress test execution.
    • timeout number A number of milliseconds the test execution will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.
    • 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.
  • Returns: TapStream
JS

M test([name][, options][, fn])

历史
版本更改
v18.8.0, v16.18.0Add a `signal` option.
v18.7.0, v16.17.0Add a `timeout` option.
v18.0.0, v16.17.0Added in: v18.0.0, v16.17.0
  • name string The name of the test, which is displayed when reporting test results. Default: The name property of fn, or '<anonymous>' if fn does not have a name.
  • options Object Configuration options for the test. The following properties are supported:
    • 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.
    • only boolean If truthy, and the test context is configured to run only tests, then this test will be run. Otherwise, the test is skipped. Default: false.
    • signal AbortSignal Allows aborting an in-progress test.
    • skip boolean | string If truthy, the test is skipped. If a string is provided, that string is displayed in the test results as the reason for skipping the test. Default: false.
    • todo boolean | string If truthy, the test marked as TODO. If a string is provided, that string is displayed in the test results as the reason why the test is TODO. Default: false.
    • timeout number A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.
  • fn Function | AsyncFunction The function under test. The first argument to this function is a TestContext object. If the test uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • Returns: Promise Resolved with undefined once the test completes.

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

The TestContext object passed to the fn argument can be used to perform actions related to the current test. Examples include skipping the test, adding additional TAP diagnostic information, or creating subtests.

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

JS

The timeout option can be used to fail the test if it takes longer than timeout milliseconds to complete. However, it is not a reliable mechanism for canceling tests because a running test might block the application thread and thus prevent the scheduled cancellation.

M describe([name][, options][, fn])

  • name string The name of the suite, which is displayed when reporting test results. Default: The name property of fn, or '<anonymous>' if fn does not have a name.
  • options Object Configuration options for the suite. supports the same options as test([name][, options][, fn]).
  • 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.
  • Returns: undefined.

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

M describe.skip([name][, options][, fn])

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

M describe.todo([name][, options][, fn])

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

M it([name][, options][, fn])

  • name string The name of the test, which is displayed when reporting test results. Default: The name property of fn, or '<anonymous>' if fn does not have a name.
  • options Object Configuration options for the suite. supports the same options as test([name][, options][, fn]).
  • 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.
  • Returns: undefined.

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

M it.skip([name][, options][, fn])

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

M it.todo([name][, options][, fn])

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

M before([fn][, options])

Added in: v18.8.0, v16.18.0

  • fn Function | AsyncFunction The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • options Object Configuration options for the hook. The following properties are supported:
    • signal AbortSignal Allows aborting an in-progress hook.
    • timeout number A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.

This function is used to create a hook running before running a suite.

JS

M after([fn][, options])

Added in: v18.8.0, v16.18.0

  • fn Function | AsyncFunction The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • options Object Configuration options for the hook. The following properties are supported:
    • signal AbortSignal Allows aborting an in-progress hook.
    • timeout number A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.

This function is used to create a hook running after running a suite.

JS

M beforeEach([fn][, options])

Added in: v18.8.0, v16.18.0

  • fn Function | AsyncFunction The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • options Object Configuration options for the hook. The following properties are supported:
    • signal AbortSignal Allows aborting an in-progress hook.
    • timeout number A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.

This function is used to create a hook running before each subtest of the current suite.

JS

M afterEach([fn][, options])

Added in: v18.8.0, v16.18.0

  • fn Function | AsyncFunction The hook function. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • options Object Configuration options for the hook. The following properties are supported:
    • signal AbortSignal Allows aborting an in-progress hook.
    • timeout number A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.

This function is used to create a hook running after each subtest of the current test.

JS

C MockFunctionContext

Added in: v19.1.0

The MockFunctionContext class is used to inspect or manipulate the behavior of mocks created via the MockTracker APIs.

M ctx.calls

Added in: v19.1.0

A getter that returns a copy of the internal array used to track calls to the mock. Each entry in the array is an object with the following properties.

  • arguments Array An array of the arguments passed to the mock function.
  • error any If the mocked function threw then this property contains the thrown value. Default: undefined.
  • result any The value returned by the mocked function.
  • stack Error An Error object whose stack can be used to determine the callsite of the mocked function invocation.
  • target Function | undefined If the mocked function is a constructor, this field contains the class being constructed. Otherwise this will be undefined.
  • this any The mocked function's this value.

M ctx.callCount()

Added in: v19.1.0

  • Returns: integer The number of times that this mock has been invoked.

This function returns the number of times that this mock has been invoked. This function is more efficient than checking ctx.calls.length because ctx.calls is a getter that creates a copy of the internal call tracking array.

M ctx.mockImplementation(implementation)

Added in: v19.1.0

This function is used to change the behavior of an existing mock.

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

JS

M ctx.mockImplementationOnce(implementation[, onCall])

Added in: v19.1.0

  • implementation Function | AsyncFunction The function to be used as the mock's implementation for the invocation number specified by onCall.
  • onCall integer The invocation number that will use implementation. If the specified invocation has already occurred then an exception is thrown. Default: The number of the next invocation.

This function is used to change the behavior of an existing mock for a single invocation. Once invocation onCall has occurred, the mock will revert to whatever behavior it would have used had mockImplementationOnce() not been called.

The following example creates a mock function using t.mock.fn(), calls the mock function, changes the mock implementation to a different function for the next invocation, and then resumes its previous behavior.

JS

M ctx.restore()

Added in: v19.1.0

Resets the implementation of the mock function to its original behavior. The mock can still be used after calling this function.

C MockTracker

Added in: v19.1.0

The MockTracker class is used to manage mocking functionality. The test runner module provides a top level mock export which is a MockTracker instance. Each test also provides its own MockTracker instance via the test context's mock property.

M mock.fn([original[, implementation]][, options])

Added in: v19.1.0

  • original Function | AsyncFunction An optional function to create a mock on. Default: A no-op function.
  • implementation Function | AsyncFunction An optional function used as the mock implementation for original. This is useful for creating mocks that exhibit one behavior for a specified number of calls and then restore the behavior of original. Default: The function specified by original.
  • options Object Optional configuration options for the mock function. The following properties are supported:
    • times integer The number of times that the mock will use the behavior of implementation. Once the mock function has been called times times, it will automatically restore the behavior of original. This value must be an integer greater than zero. Default: Infinity.
  • Returns: Proxy The mocked function. The mocked function contains a special mock property, which is an instance of MockFunctionContext, and can be used for inspecting and changing the behavior of the mocked function.

This function is used to create a mock function.

The following example creates a mock function that increments a counter by one on each invocation. The times option is used to modify the mock behavior such that the first two invocations add two to the counter instead of one.

JS

M mock.method(object, methodName[, implementation][, options])

Added in: v19.1.0

  • object Object The object whose method is being mocked.
  • methodName string | symbol The identifier of the method on object to mock. If object[methodName] is not a function, an error is thrown.
  • implementation Function | AsyncFunction An optional function used as the mock implementation for object[methodName]. Default: The original method specified by object[methodName].
  • options Object Optional configuration options for the mock method. The following properties are supported:
    • getter boolean If true, object[methodName] is treated as a getter. This option cannot be used with the setter option. Default: false.
    • setter boolean If true, object[methodName] is treated as a setter. This option cannot be used with the getter option. Default: false.
    • times integer The number of times that the mock will use the behavior of implementation. Once the mocked method has been called times times, it will automatically restore the original behavior. This value must be an integer greater than zero. Default: Infinity.
  • Returns: Proxy The mocked method. The mocked method contains a special mock property, which is an instance of MockFunctionContext, and can be used for inspecting and changing the behavior of the mocked method.

This function is used to create a mock on an existing object method. The following example demonstrates how a mock is created on an existing object method.

JS

M mock.reset()

Added in: v19.1.0

This function restores the default behavior of all mocks that were previously created by this MockTracker and disassociates the mocks from the MockTracker instance. Once disassociated, the mocks can still be used, but the MockTracker instance can no longer be used to reset their behavior or otherwise interact with them.

After each test completes, this function is called on the test context's MockTracker. If the global MockTracker is used extensively, calling this function manually is recommended.

M mock.restoreAll()

Added in: v19.1.0

This function restores the default behavior of all mocks that were previously created by this MockTracker. Unlike mock.reset(), mock.restoreAll() does not disassociate the mocks from the MockTracker instance.

C TapStream

Added in: v18.9.0

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

E 'test:diagnostic'

  • message string The diagnostic message.

Emitted when context.diagnostic is called.

E 'test:fail'

Emitted when a test fails.

E 'test:pass'

Emitted when a test passes.

C TestContext

Added in: v18.0.0, v16.17.0

An instance of TestContext is passed to each test function in order to interact with the test runner. However, the TestContext constructor is not exposed as part of the API.

M context.beforeEach([fn][, options])

Added in: v18.8.0, v16.18.0

  • fn Function | AsyncFunction The hook function. The first argument to this function is a TestContext object. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • options Object Configuration options for the hook. The following properties are supported:
    • signal AbortSignal Allows aborting an in-progress hook.
    • timeout number A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.

This function is used to create a hook running before each subtest of the current test.

JS

M context.afterEach([fn][, options])

Added in: v18.8.0, v16.18.0

  • fn Function | AsyncFunction The hook function. The first argument to this function is a TestContext object. If the hook uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • options Object Configuration options for the hook. The following properties are supported:
    • signal AbortSignal Allows aborting an in-progress hook.
    • timeout number A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.

This function is used to create a hook running after each subtest of the current test.

JS

M context.diagnostic(message)

Added in: v18.0.0, v16.17.0

  • message string Message to be displayed as a TAP diagnostic.

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

JS

M context.name

Added in: v18.8.0, v16.18.0

The name of the test.

M context.runOnly(shouldRunOnlyTests)

Added in: v18.0.0, v16.17.0

  • shouldRunOnlyTests boolean Whether or not to run only tests.

If shouldRunOnlyTests is truthy, the test context will only run tests that have the only option set. Otherwise, all tests are run. If Node.js was not started with the --test-only command-line option, this function is a no-op.

JS

M context.signal

Added in: v18.7.0, v16.17.0

  • AbortSignal Can be used to abort test subtasks when the test has been aborted.
JS

M context.skip([message])

Added in: v18.0.0, v16.17.0

  • message string Optional skip message to be displayed in TAP output.

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

JS

M context.todo([message])

Added in: v18.0.0, v16.17.0

  • message string Optional TODO message to be displayed in TAP output.

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

JS

M context.test([name][, options][, fn])

历史
版本更改
v18.8.0, v16.18.0Add a `signal` option.
v18.7.0, v16.17.0Add a `timeout` option.
v18.0.0, v16.17.0Added in: v18.0.0, v16.17.0
  • name string The name of the subtest, which is displayed when reporting test results. Default: The name property of fn, or '<anonymous>' if fn does not have a name.
  • options Object Configuration options for the subtest. The following properties are supported:
    • concurrency number The number of tests that can be run at the same time. If unspecified, subtests inherit this value from their parent. Default: 1.
    • only boolean If truthy, and the test context is configured to run only tests, then this test will be run. Otherwise, the test is skipped. Default: false.
    • signal AbortSignal Allows aborting an in-progress test.
    • skip boolean | string If truthy, the test is skipped. If a string is provided, that string is displayed in the test results as the reason for skipping the test. Default: false.
    • todo boolean | string If truthy, the test marked as TODO. If a string is provided, that string is displayed in the test results as the reason why the test is TODO. Default: false.
    • timeout number A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. Default: Infinity.
  • fn Function | AsyncFunction The function under test. The first argument to this function is a TestContext object. If the test uses callbacks, the callback function is passed as the second argument. Default: A no-op function.
  • Returns: Promise Resolved with undefined once the test completes.

This function is used to create subtests under the current test. This function behaves in the same fashion as the top level test() function.

JS

C SuiteContext

Added in: v18.7.0, v16.17.0

An instance of SuiteContext is passed to each suite function in order to interact with the test runner. However, the SuiteContext constructor is not exposed as part of the API.

M context.name

Added in: v18.8.0, v16.18.0

The name of the suite.

M context.signal

Added in: v18.7.0, v16.17.0

  • AbortSignal Can be used to abort test subtasks when the test has been aborted.