Git: avoid commits of fdescribe() and fit() (jasmine/jest tests)

While writing tests, some frameworks offers the possibility to “focus” on a particular test or particular suite by running only them and not the all of them.

While this is useful when writing the tests of some component, it can be a dangerous tool when the focus is baked within the tests themselves, such as Jasmine‘s special instructions fdescribe and fit. Indeed, if these instructions make it through the source-control, it will render the whole Continuous Testing inefficient (as part of the Continuous Integration), as some errors could pass undetected by the filtered test files.

To avoid to break Continuous Testing, we’ll add a pre-flight check before any git push.

To set-up the check, we’ll create some directories at the root of our git folder, and a pre-commit file (the check file will itself be pushed in the source control):

misc/git-hooks/pre-commit

#!/bin/sh

# Hooks to do particular checks before allowing a commit.
# Configure Git to use this file for pre-commit checks:
#   git config core.hooksPath $GIT_DIR/../misc/git-hooks/

STATUS=0

# Checking that 'fdescribe(' or 'fit(' (focus test in Angular/NestJS) are not committed by mistake.
MATCHES=$(git --no-pager diff --staged -G'[fit|fdescribe]\(' -U0 --word-diff | grep -P '\-\]\{\+(fdescribe|fit)' | wc -l)
if [ $MATCHES -gt 0 ]
then
    echo "You forgot to remove all 'fit(' or 'fdescribe(' from your test files."
    STATUS=1
fi

exit $STATUS

Check this file in the source control, and have all developper pull it in time.

Each developper must then configurer its git setting by entering the following command (the exact path might have to be adapted, depending on configurations):

git config core.hooksPath $GIT_DIR/../misc/git-hooks/

CI is now protected!

Leave a Reply

Your email address will not be published. Required fields are marked *