Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

node-core-test

> 测试质量
Open source

Node 18's node:test, as an npm package

99 stars0 likes5 views
WebsiteGitHub

About

Node 18's node:test, as an npm package

The test npm package

This is a user-land port of node:test, the experimental test runner introduced in Node.js 18. This module makes it available in Node.js 14 and later.

Minimal dependencies, with full test suite.

Differences from the core implementation:

  • Doesn't hide its own stack frames.
  • Some features require the use of --experimental-abortcontroller CLI flag to work on Node.js v14.x. It's recommended to pass NODE_OPTIONS='--experimental-abortcontroller --no-warnings' in your env if you are testing on v14.x.

Docs

Test runner

Stability: 1 - Experimental

The node:test module facilitates the creation of JavaScript tests. To access it:

javascript
import test from 'test'
javascript
const test = require('test')

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.

…

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.

javascript
test('top level test', async t => {
  await t.test('subtest 1', t => {
    assert.strictEqual(1, 1)
  })

  await t.test('subtest 2', t => {
    assert.strictEqual(2, 2)
  })
})

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 as shown in the following example.

javascript
// The skip option is used, but no message is provided.
test('skip option', { skip: true }, t => {
  // This code is never executed.
})

// The skip option is used, and a message is provided.
test('skip option with message', { skip: 'this is skipped' }, t => {
  // This code is never executed.
})

test('skip() method', t => {
  // Make sure to return here as well if the test contains additional logic.
  t.skip()
})

test('skip() method with message', t => {
  // Make sure to return here as well if the test contains additional logic.
  t.skip('this is skipped')
})

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.

javascript
describe('A thing', () => {
  it('should work', () => {
    assert.strictEqual(1, 1);
  });

  it('should be ok', () => {
    assert.strictEqual(2, 2);
  });

  describe('a nested thing', () => {
    it('should work', () => {
      assert.strictEqual(3, 3);
    });
  });
});

describe and it are imported from the test module.

javascript
import { describe, it } from 'test';
javascript
const { describe, it } = require('test');

only tests

If node--test 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.

…

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

javascript
test('test 1', async (t) => {
  await t.test('test 2');
  await t.test('test 3');
});
test('Test 4', async (t) => {
  await t.test('Test 5');
  await t.test('test 6');
});

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 results are reported 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 later to the {TestsStream}.

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 at the top level by the {TestsStream}.

javascript
test('a test that creates asynchronous activity', t => {
  setImmediate(() => {
    t.test('subtest that is created too late', t => {
      throw new Error('error1')
    })
  })

  setImmediate(() => {
    throw new Error('error2')
  })

  // The test finishes after this line.
})

Running tests from the command line

The Node.js test runner can be invoked from the command line:

bash
node--test

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
node--test test1.js test2.mjs custom_test_dir/
node--test test1.js test2.mjs custom_test_dir/

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.

javascript
import assert from 'node:assert';
import { mock, test } from 'test';
test('spies on a function', () => {
  const sum = mock.fn((a, b) => {
    return a + b;
  });
  assert.strictEqual(sum.mock.calls.length, 0);
  assert.strictEqual(sum(3, 4), 7);
  assert.strictEqual(sum.mock.calls.length, 1);
  const call = sum.mock.calls[0];
  assert.deepStrictEqual(call.arguments, [3, 4]);
  assert.strictEqual(call.result, 7);
  assert.strictEqual(call.error, undefined);
  // Reset the globally tracked mocks.
  mock.reset();
});
javascript
'use strict';
const assert = require('node:assert');
const { mock, test } = require('test');
test('spies on a function', () => {
  const sum = mock.fn((a, b) => {
    return a + b;
  });
  assert.strictEqual(sum.mock.calls.length, 0);
  assert.strictEqual(sum(3, 4), 7);
  assert.strictEqual(sum.mock.calls.length, 1);
  const call = sum.mock.calls[0];
  assert.deepStrictEqual(call.arguments, [3, 4]);
  assert.strictEqual(call.result, 7);
  assert.strictEqual(call.error, undefined);
  // Reset the globally tracked mocks.
  mock.reset();
});

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.

javascript
test('spies on an object method', (t) => {
  const number = {
    value: 5,
    add(a) {
      return this.value + a;
    },
  };
  t.mock.method(number, 'add');
  assert.strictEqual(number.add.mock.calls.length, 0);
  assert.strictEqual(number.add(3), 8);
  assert.strictEqual(number.add.mock.calls.length, 1);
  const call = number.add.mock.calls[0];
  assert.deepStrictEqual(call.arguments, [3]);
  assert.strictEqual(call.result, 8);
  assert.strictEqual(call.target, undefined);
  assert.strictEqual(call.this, number);
});

Test reporters

The

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScriptnodejstesting

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category测试质量
PricingOpen source

> Related tools

J
Jest
JavaScript 测试框架
P
Playwright
现代端到端测试框架
E
eslint-plugin-test-selectors
Enforces that data-test-id attributes are added to interactive DOM elements (JSX) to help with UI testing. JSX only.