Skip to content

Instantly share code, notes, and snippets.

@husa
Created September 8, 2015 14:39
Show Gist options
  • Save husa/87a8d8f8ae24664a1344 to your computer and use it in GitHub Desktop.
Save husa/87a8d8f8ae24664a1344 to your computer and use it in GitHub Desktop.
Git pre-commit hook to run JS Unit Test before every commit
#!/bin/sh
red="\033[0;31m"
yellow="\033[1;33m"
green="\033[1;32m"
reset="\033[0m"
read -a changed_files <<< $(git diff --cached --name-only --raw)
# check if there're any JS related files in commit
runTests=false
for file in "${changed_files[@]}"
do
extension="${file##*.}"
case $extension in js | coffee | jsx | ts | es6) runTests=true; break;;
esac
done
[[ $runTests == false ]] && exit 0;
# now if your "package.json" isn't in the root directory
# just "cd" there
# eg.
# cd folder/with/my-package
printf "${yellow}Starting Unit Tests for JS Files:${reset}\n"
# now lets run tests
# eg.
# karma start --single-run --browsers PhantomJS --reporters dots
# or
# eslint .
# or
# mocha --colors --bail
# but we'll do more general
npm test
# now if tests failed let's abort commit by "exit 1"
# if not, congratulations, commit is now in Git
testResults=$?
if [ $testResults -eq 1 ]
then
echo -e "${red}\n Tests FAILED\n\n commit ABORTED${reset}"
exit 1
else
echo -e "${green}\nOK\n${reset}"
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment