DEV Community

Cui Mingda
Cui Mingda

Posted on

How to run unit test before every git commit with husky

首先要安装husky,在安装之前先确认一下Yarn的版本,因为通过自动脚本安装,1和2的安装方法还是有点差别的。

$ yarn --version
1.22.11
Enter fullscreen mode Exit fullscreen mode

安装husky

npx husky-init
yarn
Enter fullscreen mode Exit fullscreen mode

这样操作以后,其实是自动做了一些事情,比如在package.json中增加了一个开发依赖

"devDependencies": {
  "husky": "^7.0.0"
}
Enter fullscreen mode Exit fullscreen mode

在package.json中增加了一个脚本,每一次重新部署项目可以手动执行

"scripts": {
  "prepare": "husky install"
},
Enter fullscreen mode Exit fullscreen mode

多了一个.husky目录,其中pre-commit文件对应commit之前的hook钩子,.husky/_/husky.sh就是husky的代码,钩子执行失败,就exit,达到阻止提交的目的。

还有一个改动,执行git config --list,可以看到多了一个配置

core.hookspath=.husky
Enter fullscreen mode Exit fullscreen mode

最后修改.husky/pre-commit内容,禁用jest的watch mode

yarn test --watchAll=false
Enter fullscreen mode Exit fullscreen mode

如果要彻底卸载husky,要执行以下几个操作

yarn remove husky
rm -rf .husky
git config --unset core.hooksPath
// 删除package.json中的prepare script
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)