The Git Pre-Commit Hook to Avoid Pushing Only Unit Tests In Node

  • 时间:2020-09-20 13:49:13
  • 分类:网络文摘
  • 阅读:129 次

In NodeJS unit testing frameworks such as mocha/chai, you could add .only after describe or it, so that the specific set of tests are run, which excludes/disables all other tests. For example,

1
2
3
4
5
describe.only("I just want to run these tests", function() {
   it("should work", function() {
      expect(1).to.equal(1);
   });
});
describe.only("I just want to run these tests", function() {
   it("should work", function() {
      expect(1).to.equal(1);
   });
});

Chances are, you might forget to remove the .only before you commit and push. And even worse, the code review may miss this – which in fact will disable all other tests in the Continous Integration process.

So, you can easily add a pre-commit hook check that will give you a nice warning if you try to commit some code that has .only.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Redirect output to stderr.
exec 1>&2
 
# prevent it.only or describe.only commited
if [ "$allowonlytests" != "true" ] &&
    test $(git diff --cached | grep -E "\b(it|describe).only\("  | wc -l) != 0
then
    cat <<\EOF
Error: Attempt to add it.only or describe.only - which may disable all other tests
 
If you know what you are doing you can disable this check using:
 
    git config hooks.allowonlytests true
EOF
    exit 1
fi
 
exit 0
# Redirect output to stderr.
exec 1>&2
 
# prevent it.only or describe.only commited
if [ "$allowonlytests" != "true" ] &&
    test $(git diff --cached | grep -E "\b(it|describe).only\("  | wc -l) != 0
then
    cat <<\EOF
Error: Attempt to add it.only or describe.only - which may disable all other tests
 
If you know what you are doing you can disable this check using:
 
    git config hooks.allowonlytests true
EOF
    exit 1
fi
 
exit 0

Save above as filename “pre-commit” (without the quotes) in the folder .git/hooks at your project repository. The script will exit non-zero ONE which indicates a No if there is it.only or describe.only in the diff changes. However, the command/script is smart enough (to use grep with regular expression) that will not trigger the warning if it is followed by // line comment.

You can also disable the warning by using the following:

1
git config hooks.allowonlytests true
git config hooks.allowonlytests true
git-pre-commit-hook The Git Pre-Commit Hook to Avoid Pushing Only Unit Tests In NodeJs git

git-pre-commit-hook

Here’s an eslint plugin that has the same effect.
https://www.npmjs.com/package/eslint-plugin-no-only-tests

Here is another post on the pre-push hooks to the master branch: How to Prevent Commiting to master/develop branch by Accidents using Pre-push Hooks in Git?

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
南瓜的养生功效:温润脾胃护心助眠  可以用豆浆替代牛奶来补钙吗?  早餐吃鸡蛋7大好处及快速烹调法  把虾皮作为补钙佳品还需三思而行  饮食健康:保护肝脏必吃8种蔬菜  常吃四种食物可有效排出体内毒素  哪种蔬菜是冬季餐桌上的“当家菜”  揭秘:吃腰子真能补肾壮阳吗?  冬季经常喝新鲜梨汁的九大好处  百果之王红枣的营养价值和保健功效 
评论列表
添加评论