Home > other >  Can't target test directory with jest testMatch glob pattern
Can't target test directory with jest testMatch glob pattern

Time:11-29

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?

CodePudding user response:

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/**'
  ]
  • Related