JS Vanilla Test Code Coverage

Andrea Giammarchi
3 min readJan 16, 2017
build passing & code coverage badges

There are many tutorials out there about testing JS, most of them using some testing framework such mocha, some toolchain such grunt, some other library to do this, and something else to do that.

Sometimes I have the feeling developers spend more time on configuring rather than what’s really important: tests and code coverage.

Today, as excercise, I’ve setup a code coverage badge, scoring 100%, using a tool which is available to anyone by default: console.assert(condition)

To be fair, that project was relatively simple and it came after a gist already tested in many ways, but you got the idea: it was straight forward to write tests for it, and even faster to configure it for coverage.

What You Need To Know Code Coverage

Using justconsole.assert() does not give you a score, you need a proper code parser capable of reaching every single part of your code, and IstanbulJS does that part pretty well, and it’s a zero hassle utility.

npm install --save-dev istanbul

istanbul cover test.js

You are basically done. You run exact same test you running before via npm test except you’ll see a score at the end. Replace the script part of your package.json already and check your coverage … cool?

What You Need To See Coverage On GitHub

This is already less important, but knowing there are tests, last build was OK, and the coverage is high, is the first and most important rule in chosing any third parts software you’d like to include in your project.

Making it visible helps engaging with new projects, while having no test on any software related Open Source project should be forbidden these days.

There are two free helpers here, one is called Travis Ci, a remote server used for automated continuous integration tasks, and Coveralls, which understands coverage files produced by IstanbulJS and show stats and badge.

Once you authorize your GitHub account in these two websites, all you need to do is enabling tracking of your repository, and add a .travis.yml file for Travis, and a "coveralls": "cat ./coverage/lcov.info | coveralls" under your package.json scripts which would use istanbul to cover tests.

A Repository As Example

I’ve created a vanilla-code-coverge repository configured to have the bare minimal necessary to show the build and coverage badges on the repository.

If there’s one superflous thing I might suggest, is to use consolemd as extra dev dependency, like I’ve done in classtrophobic test and others, so you can easily highlight the test name and make the OK or error colorful. So simple, and yet so nice.

Have fun testing and covering, as much as you can.

--

--

Andrea Giammarchi

Web, Mobile, IoT, and all JS things since 00's. Formerly JS engineer at @nokia, @facebook, @twitter.