34

I have a project created using Create-React-App. I am looking to add in a precommit hook to run our linter and tests with the pre-commit package.

"pre-commit": [
  "precommit-msg",
  "lint",
  "test"
],

However, since the test script runs by default in watch mode, this prevents the commit from ever actually happening. How can add the tests not in watch move in the pre-commit?

brass monkey
  • 5,841
  • 10
  • 36
  • 61
Yuschick
  • 2,642
  • 7
  • 32
  • 45

4 Answers4

44

You can use the --watchAll=false parameter. So for example you can create another script like this:

"scripts": {
  "test:nowatch": "react-scripts test --watchAll=false",
}

And then run

"pre-commit": [
  "precommit-msg",
  "lint",
  "test:nowatch"
],
Boogie
  • 750
  • 7
  • 17
16

I found a solution for my setup by adding the following script in my package.json file.

"test:nowatch": "CI=true react-scripts-ts test --env=jsdom",

"pre-commit": [
  "precommit-msg",
  "lint",
  "test:nowatch"
],

This came from the following thread: https://github.com/facebook/create-react-app/issues/2336

Yuschick
  • 2,642
  • 7
  • 32
  • 45
7

Cross platform solution for this:

  1. Install cross-env
  2. Use your test command with such props: "test:nowatch": "cross-env CI=true react-scripts test --env=jsdom --findRelatedTests"
5

Just adding the CI=true like this "test": "CI=true react-scripts test" worked for me

  • this is a very elegant solution, thanks! i just created a .env.test file and put it there, CRA supports dotenv files out of the box so i put it there – Sombriks Mar 14 '23 at 01:51