Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore certain files when running `npm test` in create-react-app?

Currently npm test is running all files that has .test.js extension. I would like some files to be ignored. Where do I configure that option? I tried

 "jest": {
        "collectCoverageFrom": [
            "src/App.test.js"
        ]
    },

in package.json. I don't see any difference.

like image 736
CKA Avatar asked Apr 11 '19 12:04

CKA


People also ask

How do I run a single file in react?

Use <script> tags and React's createElement() function to build an app in a single file. With no Redux, no Webpack, and no NPM! Have you worked with JavaScript, CSS and HTML before?


2 Answers

You might be tempted to use testPathIgnorePatterns as a cli argument, but note this causes unexpected side effects, in that it breaks the ability to run single tests with npm test TestName or npm test -- -t TestName.

This is because, as far as i can tell, testPathIgnorePatterns is incredibly greedy, in that any argument after the testPathIgnorePatterns argument will be used as a value for testPathIgnorePatterns.

For example:

If I have the following set in my package.json:

"test": "react-scripts test --testPathIgnorePatterns=e2e",

And then run: npm test MyTest

Then the resulting command is: react-scripts test --testPathIgnorePatterns=e2e "App"

And jest will be ignore both e2e and App!

A workaround I have found is to not use the testPathIgnorePatterns cli arg, and instead use the testMatch jest config.

Let's say I want to ignore all files in an e2e directory, then I could use the following regex:

"testMatch": [
  "<rootDir>/src/(?!e2e)*/**/__tests__/**/*.{js,jsx,ts,tsx}",
  "<rootDir>/src/(?!e2e)*/**/*.{spec,test}.{js,jsx,ts,tsx}"
]

Or if i wanted to only include tests in a certain directory, I can use:

"testMatch": [
  "<rootDir>/src/modules/**/__tests__/**/*.{js,jsx,ts,tsx}",
  "<rootDir>/src/modules/**/*.{spec,test}.{js,jsx,ts,tsx}"
]
like image 107
badsyntax Avatar answered Sep 28 '22 09:09

badsyntax


Create React App only allows you to override the following Jest configuration within your package.json:

"jest": {
  "collectCoverageFrom": [],
  "coverageThreshold": {},
  "coverageReporters": [],
  "snapshotSerializers": []
}

You can find the full list of override options here: https://facebook.github.io/create-react-app/docs/running-tests#configuration

Solution 1

Eject Create React App and configure by using testPathIgnorePatterns.

Solution 2

You can still override Jest's configuration by passing the --testPathIgnorePatterns option to react-scripts test.

For example:

"test": "react-scripts test --testPathIgnorePatterns=src/ignoredDirectory --env=jsdom"
like image 38
tobias Avatar answered Sep 28 '22 08:09

tobias