Source Code: lib/test.js
The node:test module facilitates the creation of JavaScript tests that\nreport results in TAP format. To access it:
node:test
import test from 'node:test';\n
const test = require('node:test');\n
This module is only available under the node: scheme. The following will not\nwork:
node:
import test from 'test';\n
const test = require('test');\n
Tests created via the test module consist of a single function that is\nprocessed in one of three ways:
test
Promise
The following example illustrates how tests are written using the\ntest module.
test('synchronous passing test', (t) => {\n // This test passes because it does not throw an exception.\n assert.strictEqual(1, 1);\n});\n\ntest('synchronous failing test', (t) => {\n // This test fails because it throws an exception.\n assert.strictEqual(1, 2);\n});\n\ntest('asynchronous passing test', async (t) => {\n // This test passes because the Promise returned by the async\n // function is 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
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.
1
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.
test()
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
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.
await
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.
skip
skip()
// 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
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.
describe
it
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
describe and it are imported from the node:test module.
import { describe, it } from 'node:test';\n
const { describe, it } = require('node:test');\n
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.
--test-only
only
runOnly()
// 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
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.
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.
setImmediate()
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.
uncaughtException
unhandledRejection
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
The Node.js test runner can be invoked from the command line by passing the\n--test flag:
--test
node --test\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.
Alternatively, one or more paths can be provided as the final argument(s) to\nthe Node.js command, as shown below.
node --test test1.js test2.mjs custom_test_dir/\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.
test1.js
test2.mjs
custom_test_dir/
When searching for test files to execute, the test runner behaves as follows:
node_modules
.js
.cjs
.mjs
^test$
'test'
test.js
test.cjs
test.mjs
^test-.+
'test-'
test-example.js
test-another-example.mjs
.+[\\.\\-\\_]test$
.test
-test
_test
example.test.js
example-test.cjs
example_test.mjs
.node
.json
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.
run({ files: [path.resolve('./tests/test.js')] })\n .pipe(process.stdout);\n
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.
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.
TestContext
fn
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.
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
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.
timeout
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.
describe()
Shorthand for skipping a suite, same as describe([name], { skip: true }[, fn]).
describe([name], { skip: true }[, fn])
Shorthand for marking a suite as TODO, same as\ndescribe([name], { todo: true }[, fn]).
TODO
describe([name], { todo: true }[, fn])
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.
it()
Shorthand for skipping a test,\nsame as it([name], { skip: true }[, fn]).
it([name], { skip: true }[, fn])
Shorthand for marking a test as TODO,\nsame as it([name], { todo: true }[, fn]).
it([name], { todo: true }[, fn])
This function is used to create a hook running before running a suite.
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
This function is used to create a hook running after running a suite.
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
This function is used to create a hook running\nbefore each subtest of the current suite.
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
This function is used to create a hook running\nafter each subtest of the current test.
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
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
run()
TapStream
Emitted when context.diagnostic is called.
context.diagnostic
Emitted when a test fails.
Emitted when a test passes.
An instance of TestContext is passed to each test function in order to\ninteract with the test runner. However, the TestContext constructor is not\nexposed as part of the API.
This function is used to create a hook running\nbefore each subtest of the current test.
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
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
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.
test('top level test', (t) => {\n t.diagnostic('A diagnostic message');\n});\n
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.
shouldRunOnlyTests
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
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.
message
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
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.
todo()
test('top level test', (t) => {\n // This test is marked as `TODO`\n t.todo('this is a todo');\n});\n
This function is used to create subtests under the current test. This function\nbehaves in the same fashion as the top level test() function.
test('top level test', async (t) => {\n await t.test(\n 'This is a subtest',\n { only: false, skip: false, concurrency: 1, todo: false },\n (t) => {\n assert.ok('some relevant assertion here');\n }\n );\n});\n
The name of the test.
test('top level test', async (t) => {\n await fetch('some/uri', { signal: t.signal });\n});\n
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.
SuiteContext
The name of the suite.