Run tests with husky pre-push only when there are changes

Viewed 4745

As in the title, at the moment I have configured my app to run tests every time a git push is executed,

"husky": {
    "hooks": {
      "pre-push": "npm run test:unit"
    }
  }

but evidently it does not scale well, the more tests the more time it will take to push, so is there a way I can trigger the tests only if there are changes in the files?


eventually I've found that Jest has a nice flag called --changedSince so you can have something like this in your package.json file:

"test:unit": "test:unit --changedSince=@{push}"

that will execute only the tests of the files that have been changed making a comparison with the remote HEAD since last push

1 Answers

A good option to achieve this is the prepush-if-changed package.
It allows you to specify a match pattern for files for which to trigger the hook when changed.

  "husky": {
    "hooks": {
      "pre-push": "prepush-if-changed"
    }
  },
  "prepush-if-changed": {
    "src/**/*.js?(x)": "npm run test:unit"
  }
Related