无法使用 jest testMatch glob 模式定位测试目录

Man*_*sur 16 testing glob directory-structure node.js jestjs

假设我有一个如下所示的项目结构:

src/index.js
src/test/foo.js
test/integration/src/index.test.js
test/unit/src/index.test.js
jest.config.json
Run Code Online (Sandbox Code Playgroud)

jest.config.json我有我的testMatch

src/index.js
src/test/foo.js
test/integration/src/index.test.js
test/unit/src/index.test.js
jest.config.json
Run Code Online (Sandbox Code Playgroud)

当我运行 jest 时,--config jest.config.json它与 0 个文件匹配。

  testMatch: test/** - 0 matches
  testPathIgnorePatterns: /node_modules/ - 5 matches
  testRegex:  - 0 matches
Pattern:  - 0 matches
Run Code Online (Sandbox Code Playgroud)

我认为这可能与一些不正确的内容有关,rootDir因为testMatch与此相关。我在调试模式下运行 jest 来查看我的根目录,看起来它是正确的。它显示了我的项目目录。(如果jest.config.json存在的话)

当我更改testMatch为它时**/test/**,它可以检测目录中的测试test/,但这不是我想要的,因为它也与src/test/目录匹配。

为什么它无法在test/目录中检测到我的测试?我的 glob 模式不正确吗?

mor*_*ney 19

为什么它无法检测到我在 test/ 目录中的测试?我的 glob 模式不正确吗?

Jest 的 glob 实现最近遇到了一些 问题。Jest 在底层使用micromatch,但为什么它会挂在相对路径 glob 上尚不清楚。

您可以在 Jest 配置中尝试以下几项操作:

  1. <rootDir>将字符串标记直接包含在您的testMatchglob 中,例如testMatch: ['<rootDir>/test/**'].
  2. 更严格地遵循 Jest testMatch 文档中的 globstar 示例,注意有关 glob 顺序的注释:

注意:每个 glob 模式都按照它们在配置中指定的顺序应用。(例如 ["! / fixtures / ", " /tests//.js " ] 不会排除Fixtures ,因为否定被第二个模式覆盖。为了使否定的 glob 在此示例中工作,它必须出现/测试//.js

  testMatch: [
    '**/test/**',
    '!**/src/**'
  ]
Run Code Online (Sandbox Code Playgroud)

  • 现在我使用 &lt;rootDir&gt;/test/** 方法。我不想使用第二个,因为它只排除 src 文件夹。 (2认同)