Automatic Node.js testing and linting using Git hooks

Published on June 29, 2017 under Blog

In Summer 2017 I was working on an internship with Microsoft and UCL. I was put in charge of designing and developing the backend architecture for a reasonably big system. Continuous integration (CI) and deployment (CD) were a must, so I tried to automate as many things as possible. As you might already know, I'm a huge Node.js fan so naturally I decided to work with this platform. When my projects involve writing JavaScript, I always insist on using linting tools (e.g. ESLint) to ensure consistent coding style throughout the source code.

Truth be told, although I always run unit tests before pushing I often forget about linting (npm run lint in most of my projects). Due to this, I sometimes push "bad" code (unused variables, inconsistent commas, etc.) to CI, which results in the whole team being notified about a build error. This article talks about avoiding this issue by using Git hooks.

Git hooks

To solve my particular issue, I decided to use a pre-push hook. I could also use a pre-commit, but I don't have any issues with inserting an extra commit fixing any linting problems. The commands I wanted to run for my particular project are npm run test-compact and npm run lint. These are executed pre-push, making sure the code I push to online repositories is working. The other command I run pre-commit is npm run apidoc followed by git add ./doc/, which scans the source code for doc blocks, generates the documentation and adds it to my commit (thanks, apiDoc).

There's an amazing NPM package called Husky that makes working with Git hooks easy for Node developers. Just a matter of adding new scripts to your package.json:

{
  "name": "...",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    //...
    "test-compact": "mocha --reporter dot \"./lib/**/*.spec.js\"",
    "lint": "eslint ./index.js ./test/ ./lib/",
    "apidoc": "apidoc -i ./lib/ -o ./doc/",
    "precommit": "npm run apidoc && git add ./doc/",
    "prepush": "npm run test-compact && npm run lint"
  },
  // ...
}

To summarise, my Git hooks now do the following:


End of Article

Timur Kuzhagaliyev Author

I'm a computer science graduate from UCL & Caltech, working as a systems engineer at Jump Trading. Before Jump, I was doing computer vision for Video Quality Analysis team at Amazon.