How to promote unit testing JavaScript with Visual Code

So you want the developers on your team to write more unit tests.

One good way is make their IDE show any non-tested code in RED.

In the image above we can see that line 8 is marked red – it hasn’t been tested.

People focus on what’s visible, and there’s nothing more visible than highlighting the code as it’s being developed 🙂

How to set it up

There are 3 simple steps…

1. Generate test coverage reports

We can do this using NYC. To install it:

npm install nyc --save-dev

If you’re running your tests using npm and Mocha then you can integrate NYC via package.json. Just add it before mocha. Here’s an example:

...
 "scripts" {
   "test": "nyc --reporter=lcov mocha"
 }
 ...

After running npm test you should see that the file “coverage/lcov.info” has been generated.

2. Install the plugin

Install the Visual Code plugin called “Coverage Gutters” by ryanluker.

You’ll need to reload after installing it.

3. Display coverage!

To display coverage:

  1. Open the command palette (SHIFT + CMD + P)
  2. Choose Coverage Gutters: Display Coverage
  3. Visual Code will display a list of coverage files, choose the one relevant to your project.

This can also be toggled via the “Watch” button in the bottom-left of Visual Code.

4. Enjoy 🙂

Now, whenever npm test is run the gutter will update accordingly.

What… you want more?

You can also have the tests run automatically after npm start. To do this add a “poststart” script in package.json. For example:

...
 "scripts" {
  "start": "node app.js",
   "poststart": "nyc --reporter=lcov mocha",
   "test": "nyc --reporter=lcov mocha"
 }
 ...

I’d love to hear how other people give visibility of test coverage… leave a comment below!

Published
Categorized as Web

Leave a Reply

%d bloggers like this: