Setting up pre-commit tests with Git

Pre-commit tests, if set up correctly, can be a valuable time saver. They can prevent bad code from getting in the repository and reduce the overall time spent in CI jobs. This example will use angular.js code, and will show how to add persistent pre-commit hooks which reject commits unless the unit tests pass.

For starters, create a bin/ directory in the top of your project to store the hook utility scripts (or some other convenient location). In this directory, create two scripts; the first one will be used to create hook symlinks (bin/create-hook-symlinks):

the other one will be a wrapper script for executing hooks (bin/hook-wrapper):

The actual hook scripts will be placed in the hooks/ directory. Create a hooks/pre-commit file with this content:

The advantage of storing hooks inside the repository is that they can be easily shared and enabled/disabled if necessary.
(note that all files created above should be set as executable)

To enable the pre-commit hook, run:

This will create a symlink in .git/hooks for each hook listed in HOOK_NAMES to bin/hook-wrapper, which will in turn run hook scripts in hooks/ based on the symlink from which it was executed.
The pre-commit hook will run unit tests with the grunt test:unit command before each commit:

This example is also available at

(info on how to build angular.js, which is a requirement for running unit tests:

Follow me

Dario Duvnjak

Throughout the years I've experienced working in all parts of the software development process on different tech stacks and with clients from all over the world. Always looking out for the next great tool in cutting edge open source technologies. I specialize in Cloud computing (AWS), Ruby, Node.js, DevOps, Docker and Puppet.
Follow me
Dario DuvnjakSetting up pre-commit tests with Git