The absolute beginner guide to unit testing in node.js
Intro
In this tutorial, we will focus on testing a simple module.
The best way to explain something is by practice. We will create a simple module in javascript and then we will test it.
Module
Let's create a simple module named append world.
- Create a folder named simple-module
- Run inside the folder
npm init -y
This will create the package.json file
- Create a file called append-world.js
With the following code:
// append-world.js
'use strict';
function appendWorld(str) {
return `${str} World`;
}
module.exports = appendWorld;
Now let's create a unit test for our module.
Unit test
The first thing we need to install our test runner.
A test runner is a very simple program that executes our tests and shows the results.
For this tutorial, we will use mocha
- Run
npm install mocha --save-dev
Next we need to create a test folder.
- Create the
test
folder - Inside
test/
createappend-world.test.js
file
// test/append-world.test.js
'use strict';
const assert = require('assert');
const appendWorld = require('../append-world.js');
describe('appendWorld', () => {
it('should append world to the end of each string', () => {
const str = 'Hello';
const expected = 'Hello World';
assert.equal(appendWorld(str), expected);
});
});
Now what we can do is to edit the package.json file and add there the following line.
"scripts": {
"test": "mocha --recursive"
},
After we can run our tests by simply using the following command:
$ npm test
mocha --recursive
appendWorld
✓ should append world to the end of each string
And we will get the output of our tests in the console.