This guide will walk you through the steps to setup git hooks (pre-commits, pre-push
) using Husky. Additionally we will be using package lint-staged
which tracks of staged code files and run jest tests related to those files on each commit.
Let's set it up!
- Install the following packages
npm install --save-dev husky lint-staged jest ts-jest @types/jest
- Add husky prepare script - Install husky on the root of project
npm set-script prepare "cd ../../ && husky install"
- Run command
npm run prepare
- Add pre-commit hook with command
lint-staged
- Run this command from the root of project
npx husky add .husky/pre-commit "npx lint-staged"
- Create
.lintstagedrc.json
on the root of folder and add following content in it
{
"src/**/*.{ts,tsx}": ["jest --bail --findRelatedTests"]
}
- Create jest config file using command
npx ts-jest config:init
- Add following content in
jest.config.js
created by above command
// eslint-disable-next-line no-undef
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src/'],
}
Now add the test files and when you staged code files and try to commit, it will automatically run the related test before commmit!