Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 922
Ayan Avatar asked Jun 28 '19 10:06

Ayan


People also ask

How do you enforce a pre-commit hook?

If you want enforcement, use an update hook in the central repo. If the hook is doing per-commit verification, you can still provide a pre-commit hook; developers will likely adopt it voluntarily, so that they can find out right away when they've done something wrong, rather than waiting until they try to push.

Can you commit pre-commit hooks?

pre-commit hooks are a mechanism of the version control system git. They let you execute code right before the commit. Confusingly, there is also a Python package called pre-commit which allows you to create and use pre-commit hooks with a way simpler interface.

How do git pre-commit hooks work?

The pre-commit script is executed every time you run git commit before Git asks the developer for a commit message or generates a commit object. You can use this hook to inspect the snapshot that is about to be 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",
    }
  }
}
like image 109
Doğancan Arabacı Avatar answered Oct 11 '22 08:10

Doğancan Arabacı