Can't target test directory with jest testMatch glob pattern
Asked Answered
F

1

18

Let's say that I have a project structure like below:

src/index.js
src/test/foo.js
test/integration/src/index.test.js
test/unit/src/index.test.js
jest.config.json

In jest.config.json I have my testMatch

{
  "testMatch": [
    "test/**"
  ]
}

When I run jest with --config jest.config.json it matches with 0 file.

  testMatch: test/** - 0 matches
  testPathIgnorePatterns: /node_modules/ - 5 matches
  testRegex:  - 0 matches
Pattern:  - 0 matches

I thought it might be related with some incorrect rootDir since testMatch is relative to that. I run jest in debug mode to see my root and it seems it's correct. It shows my project directory. (where jest.config.json exists)

When I change my testMatch to **/test/** it can detect my tests in test/ directory but that's not what I want because then it also matches with src/test/ directory.

Why it cannot detect my tests in test/ directory? Is my glob pattern incorrect?

Fright answered 28/11, 2021 at 2:26 Comment(0)
N
21

Why it cannot detect my tests in test/ directory? Is my glob pattern incorrect?

Jest's glob implementation has been going through some issues as of late. Under the hood Jest uses micromatch, but why it is getting hung up on relative path globs is unclear.

There are a couple things you can try in your Jest config:

  1. Include the <rootDir> string token directly in your testMatch glob like testMatch: ['<rootDir>/test/**'].
  2. Follow the globstar example more closely from the Jest testMatch documentation, paying attention to the note about glob order:

Note: Each glob pattern is applied in the order they are specified in the config. (For example ["!/fixtures/", "/tests//.js"] will not exclude fixtures because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after /tests//.js.)

  testMatch: [
    '**/test/**',
    '!**/src/**'
  ]
Nicholle answered 28/11, 2021 at 14:38 Comment(5)
For now I used <rootDir>/test/** approach. I don't want to use second because it just excludes src folder.Fright
I personally would have chosen option 1 myself too.Nicholle
thank you sir, adding rootDir solved it for meTypesetting
"...has been going through some issues as of late..." Those issues are closed. Now why doesn't it work? test/** doesn't match anything nor does ./test/**.Shakta
To exclude you could use testPathIgnorePatterns instead.Quito

© 2022 - 2024 — McMap. All rights reserved.