Revisiting Node.js Testing: Part 1

January 23, 2018 0 Comments

Revisiting Node.js Testing: Part 1

 

 

A walk-through of using Jest for testing in Node.js applications.

Much like how my frontend development drove my backend development towards using JavaScript (Node.js), it is now driving me to consider Jest for much of my backend testing.

Previously, my go-to Node.js backend testing solution included Mocha framework, Chai for assertions, Sinon for mocking, and Instabul for coverage. At the same time, Jest, with it’s strong support for React, became my frontend testing solution (provides the framework, assertion, mocking, and coverage solution).

The obvious question then becomes; How about Jest on the backend too? .

note: This series is not a side-by-side comparison of Jest with other solutions. It is, rather, a walk-through on using Jest for testing in a Node.js application.

All the examples in this series are available for download. They are Node.js (version ≥ 8.9.3) applications.

Setup

Create a new Node.js project and install the eslint-config-airbnb-base, and it’s peer dependencies; per documentation, package as development dependencies.

note: While not required for testing, I am using ESLint and the particularly stringent Airbnb configuration; find it difficult to write JavaScript without it now. Having ESlint support in your editor, e.g., Atom, is also particularly helpful.

Install both the jest and eslint-plugin-jest packages as development dependencies.

Configure ESLint with .eslintrc.js:

started/.eslintrc.js

module.exports = {
extends: [
'airbnb-base',
'plugin:jest/recommended',
],
plugins: [
'import',
'jest',
],
env: {
node: true,
'jest/globals': true,
},
};

To simplify running ESLint and Jest, we update package.json:

started/package.json

"main": "index.js",
"scripts": {
"lint": "eslint src/",
"test": "jest src",
"coverage": "jest --collectCoverageFrom=src/
.js --coverage src"
},
"author": "",

Getting Started

Now we write our first application in a src folder.

started/src/sum.js

module.exports = (a, b) => a + b;

started/src/index.js

/* eslint-disable no-console */
const sum = require('./sum');
console.log(sum(1, 2).toString());

At this point we can run eslint to make sure that our code passes it.

npm run lint

Now we can write a test for sum.js.

started/src/sum.test.js

const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

and run the test with:

npm run test

note: Being a special script case, npm test will also work.

and run the test with coverage with:

npm run coverage

The result is as we expect, we have 100% coverage for sum.js but 0% coverage for index.js (we did not write a test for it).

Next Steps

We continue our walk-through in Revisiting Node.js Testing: Part 2 by introducing a more real-world application (an Express application).


Tag cloud