James Loveridge – Software Engineer

Test coverage

For the future me…

Setting up test coverage

To start with this is really dependent on which testing framework that a project will be using. This will cover both Jest and Ava/Mocha (Future me will be using non-Facebook developed testing framework for side projects and for work projects go with the flow). Coveralls is free for open source projects so there's no hidden pricing. The only rule is to not make it a private repository. This article will cover Coveralls with CircleCI, other continuous integration pipelines may differ.

General

Start with installing the node-coveralls production package as a development dependency that's available on npm.

npm install node-coveralls --save-dev

Note: This can be installed as npm i -D node-coveralls if using the shorthand syntax.

Add a new script task like this below, or if the future me decides to do it in a different way then that's OK too!

{
	...
	"scripts": {
		"test": "<your test framework command>",
		"test:coverage": "<test coverage command>"
	},
	...
}

Note: The vague commands in the test and test:coverage will be covered by the respective test frameworks below.

Ava / Mocha

To start using either AVA or Mocha, this will need the node production package called nyc (via npm). To sum up what nyc does. It is a package that counts the lines in the code, and then checks for tests that will cover the lines which has been written in the code that a project may have. More information about nyc and Istanbul can be found at IstanbulJS.

  1. Install as a devDependency in the package.json.
npm install nyc --save-dev
  1. Add the command to the test:coverage task inside the scripts object in the package.json.
{
	...
	"scripts": {
		"test": "<ava or mocha command for tests>",
		"test:coverage": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
	}
	...
}

What this will do is with your npm test script, it will run either how the project has been set up with AVA or Mocha. The coverage is run concurrently with the tests at the same time. I'd suggest adding the following lines to the .gitignore file:

.nyc_output
coverage

So that the git history is kept clean of auto-generated files, and this is not really needed on the repository.

Jest

Jest comes with its own built in coverage tool, so this requires one less dependency as it will not need nyc. To run the coverage with Jest and to upload to Coveralls, see below:

{
	...
	"scripts": {
		"test": "<jest command for tests>",
		"test:coverage":"jest --coverage --coverageReporters=text-lcov | coveralls"
	},
	...
}

Useful links

Read the documentation future me!

  1. Coveralls Documentation
  2. CircleCI Documentation

Until then πŸ‘‹

21 February 2020
Return to home