Saturday, January 23, 2021

In this tutorial I’m going to do the very basic to setup a testing suit, in later blog post I’ll expand on this knowledge to create a more complete and automated testing environment.

To start open terminal or command line on Windows in a clean directory and type npm init

To create a package.json file, here accept all the defaults by clicking enter on all the steps.

Navigate to that directory using your favorite editor and create a new directory math-utils. Also create a math.utils.js file inside.

Add this code to it.

let add = (number1, number2) => {
  return number1 + number2;

module.exports = {

Here we have a very basic function that add two numbers.

With this in place let’s explore testing this code. We are going to use Mocha Framework which is a very popular that will let us configure all out test case and run all our test files.

You can find mocha in

To install mocha type this command in your terminal:

npm i mocha –save-dev

Now with mocha installed let’s create our test file in the same directory as our math.utils.js file.

Add this code into math.utils.test.js

const mathUtils = require('./math.utils');

it('should add two numbers', () => {    
  let result = mathUtils.add(10, 40);

Here we have a test case, which is just a function that runs some code, if things go well the test is considered to has passed otherwise it is considered a failing test.

To create a test case, we use it which is a function provided by mocha we are going to be running our project test file through mocha, so there is not need to import it here.

It lets us define a test case, the first parameter is a string description that lets us define what this test case is doing. The second argument is a function where we need to add the code that test that out add function works as expected.

The next step is to run this test file, in order to do that we are going to configure this inside package.json.

Here in line 7 we are going to be calling mocha with one single argument which is the path expression for the files we want to test.

Here simple we are using the glob pattern

to specify multiple files, in this case we are using **/*.test.js which mean look in every single file ending in .test.js.

We can now just run our test with npm test command.

We can now just run our test with npm test command.

As you can see we have a passing test but in our case we are not really testing anything useful since our test will always pass. In order to make a useful test we should add something like this: