Jest: testRegex not working

Created on 29 Sep 2017  ยท  4Comments  ยท  Source: facebook/jest

Do you want to request a feature or report a bug?
report a bug

"jest": "21.2.1"

What is the current behavior?
Test suite failed to run

 FAIL  __tests__/setup.js

What is the expected behavior?

It should be ignoring files that doesn't present .test or .spec

Inside my package.json

  "jest": {
    "preset": "react-native",
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts|tsx)?$",
    "setupFiles": [
      "./__tests__/setup.js"
    ],
    "moduleFileExtensions": [
      "js",
      "ts",
      "tsx",
      "json"
    ],
    "transform": {
      "^.+\\.js?$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.ts?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "moduleNameMapper": {
      "^~components/(.*)": "<rootDir>/src/components/$1",
      "^~services/(.*)": "<rootDir>/src/services/$1"
    }
  }

I also tried

    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.js?$",

I'm following the configuration.html#testregex-string

Most helpful comment

I was believing that it should be ignoring those non .spec files.

โ”œโ”€โ”€ __tests__
โ”‚   โ””โ”€โ”€ component.spec.js # test
โ”‚   โ””โ”€โ”€ anything # test
โ”œโ”€โ”€ package.json # not test
โ”œโ”€โ”€ foo.test.js # test
โ”œโ”€โ”€ bar.spec.jsx # test
โ””โ”€โ”€ component.js # not test

Anyway changing the expression to /__tests__/.*.spec.(js|ts|tsx)?$ worked.

All 4 comments

Look at your regex once more, you're explicitly tell jest to search tests in __tests__ directory.

That's right; and inside there's setup.js which It shouldn't be running as a test.

I was believing that it should be ignoring those non .spec files.

โ”œโ”€โ”€ __tests__
โ”‚   โ””โ”€โ”€ component.spec.js # test
โ”‚   โ””โ”€โ”€ anything # test
โ”œโ”€โ”€ package.json # not test
โ”œโ”€โ”€ foo.test.js # test
โ”œโ”€โ”€ bar.spec.jsx # test
โ””โ”€โ”€ component.js # not test

Anyway changing the expression to /__tests__/.*.spec.(js|ts|tsx)?$ worked.

I think the reason the example regex doesn't work is due to how nodejs handles certain special characters. '/' is technically a special character and should be preceeded by a backslash.

Only certain interpreters may handle '/' differently - , (cmd, node, IDE: atom, sublime, vscode, browsers - chrome, ie, other devices).

This works:

'/__tests__/.*\\.(spec|test)\\.[tj]sx?$'

This doesn't:

'\\/__tests__\\/.*\\.(spec|test)\\.[tj]sx?$'
Was this page helpful?
0 / 5 - 0 ratings