Node.js v16.20.0 文档


测试运行器#

¥Test runner

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

源代码: lib/test.js

node:test 模块有助于创建以 TAP 格式报告结果的 JavaScript 测试。要访问它:

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

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

此模块仅在 node: 协议下可用。以下将不起作用:

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

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

通过 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. 返回 Promise 的函数,如果 Promise 拒绝,则认为该函数失败,如果 Promise 解决,则认为该函数通过。

    ¥A function that returns a Promise that is considered failing if the Promise rejects, and is considered passing if the Promise resolves.

  3. 接收回调函数的函数。如果回调接收到任何真值作为其第一个参数,则认为测试失败。如果非真值作为第一个参数传给回调,则认为测试通过。如果测试函数接收到回调函数并且还返回 Promise,则测试将失败。

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

以下示例说明了如何使用 test 模块编写测试。

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

test('synchronous passing test', (t) => {
  // This test passes because it does not throw an exception.
  assert.strictEqual(1, 1);
});

test('synchronous failing test', (t) => {
  // This test fails because it throws an exception.
  assert.strictEqual(1, 2);
});

test('asynchronous passing test', async (t) => {
  // This test passes because the Promise returned by the async
  // function is not rejected.
  assert.strictEqual(1, 1);
});

test('asynchronous failing test', async (t) => {
  // This test fails because the Promise returned by the async
  // function is rejected.
  assert.strictEqual(1, 2);
});

test('failing test using Promises', (t) => {
  // Promises can be used directly as well.
  return new Promise((resolve, reject) => {
    setImmediate(() => {
      reject(new Error('this will cause the test to fail'));
    });
  });
});

test('callback passing test', (t, done) => {
  // done() is the callback function. When the setImmediate() runs, it invokes
  // done() with no arguments.
  setImmediate(done);
});

test('callback failing test', (t, done) => {
  // When the setImmediate() runs, done() is invoked with an Error object and
  // the test fails.
  setImmediate(() => {
    done(new Error('callback failure'));
  });
}); 

当测试文件执行时,TAP 被写入 Node.js 进程的标准输出。任何理解 TAP 格式的测试工具都可以解释此输出。如果任何测试失败,则进程退出代码设置为 1

¥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

测试上下文的 test() 方法允许创建子测试。此方法的行为与顶层 test() 函数相同。以下示例演示了如何创建具有两个子测试的顶层测试。

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

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);
  });
}); 

在本示例中,await 用于确保两个子测试均已完成。这是必要的,因为父测试不会等待子测试完成。当父测试完成时仍然未完成的任何子测试将被取消并视为失败。任何子测试失败都会导致父测试失败。

¥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

可以通过将 skip 选项传递给测试或调用测试上下文的 skip() 方法来跳过单个测试。这两个选项都支持包含在 TAP 输出中显示的消息,如以下示例所示。

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

// 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 语法#

¥describe/it syntax

运行测试也可以使用 describe 来声明套件和 it 来声明测试。套件用于将相关测试组织和分组在一起。ittest 的别名,只是没有通过测试上下文,因为嵌套是使用套件完成的。

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

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);
    });
  });
}); 

describeit 是从 node:test 模块导入的。

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

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

only 测试#

¥only tests

如果 Node.js 使用 --test-only 命令行选项启动,则可以通过将 only 选项传给应该运行的测试来跳过除选定子集之外的所有顶层测试。当运行带有 only 选项集的测试时,所有子测试也会运行。测试上下文的 runOnly() 方法可用于在子测试级别实现相同的行为。

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

// Assume Node.js is run with the --test-only command-line option.
// The 'only' option is set, so this test is run.
test('this test is run', { only: true }, async (t) => {
  // Within this test, all subtests are run by default.
  await t.test('running subtest');

  // The test context can be updated to run subtests with the 'only' option.
  t.runOnly(true);
  await t.test('this subtest is now skipped');
  await t.test('this subtest is run', { only: true });

  // Switch the context back to execute all tests.
  t.runOnly(false);
  await t.test('this subtest is now run');

  // Explicitly do not run these tests.
  await t.test('skipped subtest 3', { only: false });
  await t.test('skipped subtest 4', { skip: true });
});

// The 'only' option is not set, so this test is skipped.
test('this test is not run', () => {
  // This code is not run.
  throw new Error('fail');
}); 

无关的异步活动#

¥Extraneous asynchronous activity

一旦测试函数完成执行,TAP 结果将尽快输出,同时保持测试的顺序。但是,测试函数可能会生成比测试本身寿命更长的异步活动。测试运行器处理此类活动,但不会延迟报告测试结果以适应它。

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

在下面的示例中,测试完成时仍然有两个 setImmediate() 操作未完成。第一个 setImmediate() 尝试创建新的子测试。因为父测试已经完成并输出结果,新的子测试立即被标记为失败,并在文件的 TAP 输出的顶层报告。

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

第二个 setImmediate() 创建了 uncaughtException 事件。源自已完成测试的 uncaughtExceptionunhandledRejection 事件由 test 模块处理,并在文件的 TAP 输出的顶层报告为诊断警告。

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

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

可以通过传入 --test 标志从命令行调用 Node.js 测试运行程序:

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

node --test 

默认情况下,Node.js 将递归搜索当前目录以查找匹配特定命名约定的 JavaScript 源文件。匹配文件作为测试文件执行。有关预期测试文件命名约定和行为的更多信息,请参见 测试运行器执行模型 部分。

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

或者,可以提供一个或多个路径作为 Node.js 命令的最终参数,如下所示。

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

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

在本例中,测试运行程序将执行文件 test1.jstest2.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 目录。

    ¥node_modules directories are skipped unless explicitly provided by the user.

  • 如果遇到名为 test 的目录,则测试运行程序将递归搜索所有 .js.cjs.mjs 文件。所有这些文件都被视为测试文件,不需要匹配下面详述的特定命名约定。这是为了适应将所有测试放在单个 test 目录中的项目。

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

  • 在所有其他目录中,匹配以下模式的 .js.cjs.mjs 文件被视为测试文件:

    ¥In all other directories, .js, .cjs, and .mjs files matching the following patterns are treated as test files:

    • ^test$ - 基本名称为字符串 'test' 的文件。示例:test.js, test.cjs, test.mjs.

      ¥^test$ - Files whose basename is the string 'test'. Examples: test.js, test.cjs, test.mjs.

    • ^test-.+ - 基本名称以字符串 'test-' 后跟一个或多个字符开头的文件。示例:test-example.js, test-another-example.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$ - 基本名称以 .test-test_test 结尾且前面有一个或多个字符的文件。示例:example.test.js, example-test.cjs, example_test.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.

    • Node.js 理解的其他文件类型,例如 .node.json,不会由测试运行程序自动执行,但如果在命令行上显式地提供,则支持。

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

每个匹配的测试文件都在单独的子进程中执行。如果子进程以退出代码 0 结束,则认为测试通过。否则,认为测试失败。测试文件必须是 Node.js 可执行文件,但不需要在内部使用 node:test 模块。

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

run([options])#

  • options <Object> 运行测试的配置选项。支持以下属性:

    ¥options <Object> Configuration options for running tests. The following properties are supported:

    • concurrency <number> | <boolean> 如果提供了一个数字,那么那么多文件将并行运行。如果为真,它将并行运行(CPU 核心数 - 1)个文件。如果为假,它一次只会运行一个文件。如果未指定,则子测试从其父测试继承此值。默认值:true

      ¥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> 包含要运行的文件列表的数组。测试运行器执行模型 中的默认匹配文件。

      ¥files: <Array> An array containing the list of files to run. Default matching files from test runner execution model.

    • signal <AbortSignal> 允许中止正在进行的测试执行。

      ¥signal <AbortSignal> Allows aborting an in-progress test execution.

    • timeout <number> 测试执行将在几毫秒后失败。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

      ¥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> 设置测试子进程的检查器端口。这可以是数字,也可以是不带参数并返回数字的函数。如果提供了一个空值,每个进程都有自己的端口,从主进程的 process.debugPort 递增。默认值:undefined

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

  • 返回:<TapStream>

    ¥Returns: <TapStream>

run({ files: [path.resolve('./tests/test.js')] })
  .pipe(process.stdout); 

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

  • name <string> 测试的名称,报告测试结果时显示。默认值:fnname 属性,如果 fn 没有名称,则为 '<anonymous>'

    ¥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> 测试的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the test. The following properties are supported:

    • concurrency <number> | <boolean> 如果提供了一个数字,则多个测试将并行运行。如果为真,它将并行运行(CPU 核心数 - 1)测试。对于子测试,它将是 Infinity 并行测试。如果为假,它一次只会运行一个测试。如果未指定,则子测试从其父测试继承此值。默认值:false

      ¥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> 如果为真,并且测试上下文配置为运行 only 测试,则将运行此测试。否则跳过测试。默认值: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> 允许中止正在进行的测试。

      ¥signal <AbortSignal> Allows aborting an in-progress test.

    • skip <boolean> | <string> 如果为真,则跳过测试。如果提供了字符串,则该字符串将作为跳过测试的原因显示在测试结果中。默认值:false

      ¥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> 如果为真,则测试标记为 TODO。如果提供了字符串,则该字符串会显示在测试结果中作为测试为 TODO 的原因。默认值: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> 测试失败的毫秒数。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

      ¥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> 被测试的函数。此函数的第一个参数是 TestContext 对象。如果测试使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

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

  • 返回:<Promise> 测试完成后使用 undefined 解决。

    ¥Returns: <Promise> Resolved with undefined once the test completes.

test() 函数是从 test 模块导入的值。每次调用此函数都会导致在 TAP 输出中创建一个测试点。

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

传给 fn 参数的 TestContext 对象可用于执行与当前测试相关的操作。示例包括跳过测试、添加额外的 TAP 诊断信息或创建子测试。

¥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() 返回 Promise,一旦测试完成就解决。返回值通常可以被顶层测试丢弃。但是,应该使用子测试的返回值来防止父测试先完成并取消子测试,如下例所示。

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

test('top level test', async (t) => {
  // The setTimeout() in the following subtest would cause it to outlive its
  // parent test if 'await' is removed on the next line. Once the parent test
  // completes, it will cancel any outstanding subtests.
  await t.test('longer running subtest', async (t) => {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, 1000);
    });
  });
}); 

如果完成时间超过 timeout 毫秒,则可以使用 timeout 选项使测试失败。但是,它不是取消测试的可靠机制,因为正在运行的测试可能会阻塞应用线程,从而阻止预定的取消。

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

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

  • name <string> 套件名称,报告测试结果时显示。默认值:fnname 属性,如果 fn 没有名称,则为 '<anonymous>'

    ¥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> 套件的配置选项。支持与 test([name][, options][, fn]) 相同的选项。

    ¥options <Object> Configuration options for the suite. supports the same options as test([name][, options][, fn]).

  • fn <Function> | <AsyncFunction> 套件下的函数声明所有子测试和子套件。此函数的第一个参数是 SuiteContext 对象。默认值:空操作函数。

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

  • 返回:undefined

    ¥Returns: undefined.

node:test 模块导入的 describe() 函数。每次调用此函数都会导致在 TAP 输出中创建子测试和测试点。调用顶层 describe 函数后,所有顶层测试和套件都将执行。

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

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

跳过套件的简写,与 describe([name], { skip: true }[, fn]) 相同。

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

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

将套件标记为 TODO 的简写,与 describe([name], { todo: true }[, fn]) 相同。

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

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

  • name <string> 测试的名称,报告测试结果时显示。默认值:fnname 属性,如果 fn 没有名称,则为 '<anonymous>'

    ¥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> 套件的配置选项。支持与 test([name][, options][, fn]) 相同的选项。

    ¥options <Object> Configuration options for the suite. supports the same options as test([name][, options][, fn]).

  • fn <Function> | <AsyncFunction> 被测试的函数。如果测试使用回调,则回调函数作为参数传递。默认值:空操作函数。

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

  • 返回:undefined

    ¥Returns: undefined.

it() 函数是从 node:test 模块导入的值。每次调用此函数都会导致在 TAP 输出中创建一个测试点。

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

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

跳过测试的简写,与 it([name], { skip: true }[, fn]) 相同。

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

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

将测试标记为 TODO 的简写,与 it([name], { todo: true }[, fn]) 相同。

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

before([, fn][, options])#

  • fn <Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

    ¥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> 钩子的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the hook. The following properties are supported:

    • signal <AbortSignal> 允许中止正在进行的钩子。

      ¥signal <AbortSignal> Allows aborting an in-progress hook.

    • timeout <number> 钩子会在几毫秒后失败。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

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

describe('tests', async () => {
  before(() => console.log('about to run some test'));
  it('is a subtest', () => {
    assert.ok('some relevant assertion here');
  });
}); 

after([, fn][, options])#

  • fn <Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

    ¥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> 钩子的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the hook. The following properties are supported:

    • signal <AbortSignal> 允许中止正在进行的钩子。

      ¥signal <AbortSignal> Allows aborting an in-progress hook.

    • timeout <number> 钩子会在几毫秒后失败。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

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

describe('tests', async () => {
  after(() => console.log('finished running tests'));
  it('is a subtest', () => {
    assert.ok('some relevant assertion here');
  });
}); 

beforeEach([, fn][, options])#

  • fn <Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

    ¥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> 钩子的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the hook. The following properties are supported:

    • signal <AbortSignal> 允许中止正在进行的钩子。

      ¥signal <AbortSignal> Allows aborting an in-progress hook.

    • timeout <number> 钩子会在几毫秒后失败。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

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

describe('tests', async () => {
  beforeEach(() => t.diagnostic('about to run a test'));
  it('is a subtest', () => {
    assert.ok('some relevant assertion here');
  });
}); 

afterEach([, fn][, options])#

  • fn <Function> | <AsyncFunction> 钩子函数。如果钩子使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

    ¥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> 钩子的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the hook. The following properties are supported:

    • signal <AbortSignal> 允许中止正在进行的钩子。

      ¥signal <AbortSignal> Allows aborting an in-progress hook.

    • timeout <number> 钩子会在几毫秒后失败。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

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

describe('tests', async () => {
  afterEach(() => t.diagnostic('about to run a test'));
  it('is a subtest', () => {
    assert.ok('some relevant assertion here');
  });
}); 

类:TapStream#

¥Class: TapStream

成功调用 run() 方法将返回一个新的 <TapStream> 对象,流式传输 TAP 输出 TapStream 将按照测试定义的顺序触发事件

¥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

事件:'test:diagnostic'#

¥Event: 'test:diagnostic'

调用 context.diagnostic 时触发。

¥Emitted when context.diagnostic is called.

事件:'test:fail'#

¥Event: 'test:fail'

测试失败时触发。

¥Emitted when a test fails.

事件:'test:pass'#

¥Event: 'test:pass'

测试通过时触发。

¥Emitted when a test passes.

类:TestContext#

¥Class: TestContext

TestContext 的实例被传给每个测试函数,以便与测试运行器交互。但是,TestContext 构造函数没有作为 API 的一部分公开。

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

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

  • fn <Function> | <AsyncFunction> 钩子函数。此函数的第一个参数是 TestContext 对象。如果钩子使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

    ¥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> 钩子的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the hook. The following properties are supported:

    • signal <AbortSignal> 允许中止正在进行的钩子。

      ¥signal <AbortSignal> Allows aborting an in-progress hook.

    • timeout <number> 钩子会在几毫秒后失败。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

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

test('top level test', async (t) => {
  t.beforeEach((t) => t.diagnostic(`about to run ${t.name}`));
  await t.test(
    'This is a subtest',
    (t) => {
      assert.ok('some relevant assertion here');
    }
  );
}); 

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

  • fn <Function> | <AsyncFunction> 钩子函数。此函数的第一个参数是 TestContext 对象。如果钩子使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

    ¥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> 钩子的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the hook. The following properties are supported:

    • signal <AbortSignal> 允许中止正在进行的钩子。

      ¥signal <AbortSignal> Allows aborting an in-progress hook.

    • timeout <number> 钩子会在几毫秒后失败。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

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

test('top level test', async (t) => {
  t.afterEach((t) => t.diagnostic(`finished running ${t.name}`));
  await t.test(
    'This is a subtest',
    (t) => {
      assert.ok('some relevant assertion here');
    }
  );
}); 

context.diagnostic(message)#

  • message <string> 要显示为 TAP 诊断的消息。

    ¥message <string> Message to be displayed as a TAP diagnostic.

此函数用于将 TAP 诊断写入输出。任何诊断信息都包含在测试结果的末尾。此函数不返回值。

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

test('top level test', (t) => {
  t.diagnostic('A diagnostic message');
}); 

context.name#

测试名称。

¥The name of the test.

context.runOnly(shouldRunOnlyTests)#

  • shouldRunOnlyTests <boolean> 是否运行 only 测试。

    ¥shouldRunOnlyTests <boolean> Whether or not to run only tests.

如果 shouldRunOnlyTests 为真,则测试上下文将只运行设置了 only 选项的测试。否则,将运行所有测试。如果 Node.js 不是使用 --test-only 命令行选项启动的,则此函数是无操作的。

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

test('top level test', (t) => {
  // The test context can be set to run subtests with the 'only' option.
  t.runOnly(true);
  return Promise.all([
    t.test('this subtest is now skipped'),
    t.test('this subtest is run', { only: true }),
  ]);
}); 

context.signal#

  • <AbortSignal> 可用于在测试中止时中止测试子任务。

    ¥<AbortSignal> Can be used to abort test subtasks when the test has been aborted.

test('top level test', async (t) => {
  await fetch('some/uri', { signal: t.signal });
}); 

context.skip([message])#

  • message <string> 在 TAP 输出中显示的可选跳过消息。

    ¥message <string> Optional skip message to be displayed in TAP output.

此函数使测试的输出指示测试已跳过。如果提供了 message,它将包含在 TAP 输出中。调用 skip() 不会终止测试函数的执行。此函数不返回值。

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

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

context.todo([message])#

  • message <string> 要在 TAP 输出中显示的可选 TODO 消息。

    ¥message <string> Optional TODO message to be displayed in TAP output.

此函数将 TODO 指令添加到测试的输出中。如果提供了 message,它将包含在 TAP 输出中。调用 todo() 不会终止测试函数的执行。此函数不返回值。

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

test('top level test', (t) => {
  // This test is marked as `TODO`
  t.todo('this is a todo');
}); 

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

  • name <string> 子测试的名称,在报告测试结果时显示。默认值:fnname 属性,如果 fn 没有名称,则为 '<anonymous>'

    ¥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> 子测试的配置选项。支持以下属性:

    ¥options <Object> Configuration options for the subtest. The following properties are supported:

    • concurrency <number> 可以同时运行的测试数。如果未指定,则子测试从其父测试继承此值。默认值:1

      ¥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> 如果为真,并且测试上下文配置为运行 only 测试,则将运行此测试。否则跳过测试。默认值: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> 允许中止正在进行的测试。

      ¥signal <AbortSignal> Allows aborting an in-progress test.

    • skip <boolean> | <string> 如果为真,则跳过测试。如果提供了字符串,则该字符串将作为跳过测试的原因显示在测试结果中。默认值:false

      ¥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> 如果为真,则测试标记为 TODO。如果提供了字符串,则该字符串会显示在测试结果中作为测试为 TODO 的原因。默认值: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> 测试失败的毫秒数。如果未指定,则子测试从其父测试继承此值。默认值:Infinity

      ¥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> 被测试的函数。此函数的第一个参数是 TestContext 对象。如果测试使用回调,则回调函数作为第二个参数传入。默认值:空操作函数。

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

  • 返回:<Promise> 测试完成后使用 undefined 解决。

    ¥Returns: <Promise> Resolved with undefined once the test completes.

此函数用于在当前测试下创建子测试。此函数的行为方式与顶层的 test() 函数相同。

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

test('top level test', async (t) => {
  await t.test(
    'This is a subtest',
    { only: false, skip: false, concurrency: 1, todo: false },
    (t) => {
      assert.ok('some relevant assertion here');
    }
  );
}); 

类:SuiteContext#

¥Class: SuiteContext

SuiteContext 的实例被传给每个套件函数,以便与测试运行器进行交互。但是,SuiteContext 构造函数没有作为 API 的一部分公开。

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

context.name#

套件名称。

¥The name of the suite.

context.signal#

  • <AbortSignal> 可用于在测试中止时中止测试子任务。

    ¥<AbortSignal> Can be used to abort test subtasks when the test has been aborted.

Node.js 中文网 - 粤ICP备13048890号