Git pre-commit hook that fails if “it.only” used (Jest/Jasmine)

One of the annoying things with Jest is that while it enables you to run only a single test by using it.only, it does not report this in any noticeable way. Thus you can end up in the same situation as we did, not running many tests without knowing it. (Oh yeah, if we only did review the code properly …).

This git pre-commit hook will fail when you introduce it.only into the code:


#!/bin/sh
# A git pre-commit hook that verifies that the change does not introduce
# the use of a Jest/Jasmine exclusive test via 'it.only(..)', which would
# prevent most other tests from being run without any clear indication thereof
# Redirect output to stderr.
exec 1>&2
ADDED_IT_ONLY=$(git diff -U0 –cached -S"(\W|^)it\.only\s+?\(" –pickaxe-regex | egrep "(^\+.*it.only)|\+{3}")
if [ -n "$ADDED_IT_ONLY" ]; then
echo "PRE-COMIT CHECK FAILED: You have added calls to it.only(..) thus preventing other tests from running, please fix: $ADDED_IT_ONLY"
exit 1
fi

view raw

pre-commit

hosted with ❤ by GitHub

Published by Jakub Holý

I’m a JVM-based developer since 2005, consultant, and occasionally a project manager, working currently with Iterate AS in Norway.

4 thoughts on “Git pre-commit hook that fails if “it.only” used (Jest/Jasmine)

  1. We are failing build when somebody left in tests ddescribe and iit 🙂 (we use karma with jasmine). This kind of Git pre-commit hook we are using for forcing prefix of commit messages with Jira Task ID.

      1. We are using maven and we have checkVisualTests.sh script next to pom.xml. In pom.xml we configured exec-maven-plugin to run this shell script in the test phase. If this script returns exit code different from 1, build fails.

        Script is simple, just few greps 🙂 But it works really good, only with one exception – multiline comment, but we have some rule, that even multiline comment should be same as single line (/* */ vs. //)


        #!/bin/bash
        PATH_TO_VISUAL_TESTS=src/test/visual/spec/*Spec.js
        NEWLINE=$'\n'
        OUTPUT=""
        function checkFileFor {
        visualTestFile=$1
        value=$2
        contains=$(cat ${visualTestFile} | grep -vE "([[:space:]]*)//([[:space:]]*)${value}" | grep -nE "${value}")
        if [ -n "$contains" ]; then
        echo "${NEWLINE}${NEWLINE}Visual test ${visualTestFile} contains $value:${NEWLINE}${contains}"
        fi
        }
        for visualTestFile in ${PATH_TO_VISUAL_TESTS}
        do
        OUTPUT=${OUTPUT}$(checkFileFor ${visualTestFile} "ddescribe")
        OUTPUT=${OUTPUT}$(checkFileFor ${visualTestFile} "iit")
        OUTPUT=${OUTPUT}$(checkFileFor ${visualTestFile} "pause\(\)\;")
        done
        if [ -n "$OUTPUT" ]; then
        echo "Fatal Errors Found in Visual Tests${OUTPUT}"
        exit 1
        fi
        exit 0

        view raw

        gistfile1.sh

        hosted with ❤ by GitHub

Comments are closed.