How to run a git pre-commit hook to enforce that test coverage for the staged files doesn't decrease?

Viewed 5655

I am using jest and istanbul in my ReactJS project to write test cases and check on the test coverage.

How do I ensure using a pre-commit hook that test coverage for any file, that I have staged to git, doesn't decrease from its current value before its committed?

1 Answers

You should check coverageThreshold documentation of jest from here

Below options are possible for global coverage threshold and file name pattern thresholds.

{
  ...
  "jest": {
    "coverageThreshold": {
      "global": {
        "branches": 50,
        "functions": 50,
        "lines": 50,
        "statements": 50
      },
      "./src/components/": {
        "branches": 40,
        "statements": 40
      },
      "./src/reducers/**/*.js": {
        "statements": 90
      },
      "./src/api/very-important-module.js": {
        "branches": 100,
        "functions": 100,
        "lines": 100,
        "statements": 100
      }
    }
  }
}

You can combine this with lint staged and husky to make the check in pre-commit.

In the end, your package.json would look like this:

{
  ...package.json
  "husky": {
    "hooks": {
      "pre-commit": "jest",
    }
  }
}
Related