Ask Question

Is there a way to run affected Jest Tests before every commit?

I would like to run my Jest Tests before every commit, but because running all of my Jest Tests would take very long, it would be nice if I can only run the tests affected by the files I've changed with my commit.

JavaScriptjesttestingGitlint-staged

1892 views

Authorยดs Dominik Sumer image

Dominik Sumer

Last edited on

1 Answer available

Best answer

Ok, together with ๐Ÿšซ๐Ÿ’ฉlint-staged and the built-in Jest argument --findRelatedTests this is actually pretty easy!

As you can see here, Jest has an CLI parameter in order to run only related tests for the files you pass to Jest: https://jestjs.io/docs/en/cli#--findrelatedtests-spaceseparatedlistofsourcefiles

And as awesome as lint-staged is, it passes all the changed files to the CLI commands you've provided ๐Ÿ˜

So your preferred lint-staged config should look like this:

...
"lint-staged": {
  "*.{js,jsx,ts,tsx}": [
    "jest --findRelatedTests",
  ]
}
...

This will look for changed js, jsx, ts and tsx files in your staged git files before you commit them, and will run all you related Jest tests. If any test is failing, lint-staged will make sure you're not committing bad code to your repo. ๐Ÿฅณ

๐Ÿ‘
2