测试运行器执行模型
当搜索要执行的测试文件时,测试运行器的行为如下:
- 执行用户显式提供的任何文件。
- 如果用户没有显式地指定任何路径,则递归搜索当前工作目录中指定的文件,如以下步骤所示。
- 除非用户显式地提供,否则跳过
node_modules
目录。 - 如果遇到名为
test
的目录,则测试运行程序将递归搜索所有.js
、.cjs
和.mjs
文件。 所有这些文件都被视为测试文件,不需要匹配下面详述的特定命名约定。 这是为了适应将所有测试放在单个test
目录中的项目。 - 在所有其他目录中,匹配以下模式的
.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.js 理解的其他文件类型,例如
.node
和.json
,不会由测试运行程序自动执行,但如果在命令行上显式地提供,则支持。
每个匹配的测试文件都在单独的子进程中执行。
如果子进程以退出代码 0 结束,则认为测试通过。
否则,认为测试失败。
测试文件必须是 Node.js 可执行文件,但不需要在内部使用 node:test
模块。
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 singletest
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.