Codementor Events

Demystifying Testing for newbies (Part 1)

Published Nov 23, 2017Last updated Jul 16, 2018
Demystifying Testing for newbies (Part 1)

This is an article series that aims to demystify testing and explain how to implement TDD (Test Driven Development) in our development workflow

In application development, testing is very essential mainly because it helps you to ensure that your code runs as expected and is free from errors.

A lot people find it intimidating and difficult at first glance though. To be be honest, I also did.
When I first heard about it, I spent hours reading articles which explains and illustrates how it works, but I didn’t even have enough basic knowledge to absorb the information in them. I found them too complex to understand.

Therefore, this tutorial focuses on testing in NodeJS applications which could be applied to other JavaScript environments in its basic form.

Let’s get started?
Yeah, the aha moment is finally here! You’ve heard enough stories and probably read enough articles.

So, let’s dive straight into it. Now we will take this step by step and I will advise you to follow along.

  1. Create a new directory. You can name it test-tutorial.
    Create package.json like this:
npm init
  1. Create a directory structure like this:
test-tutorial
|-utils
|   |-utils.js
|   |-utils.test.js
|-index.js
|-package.json

You can run the command below to take care of steps one and two.

mkdir test-tutorial && cd test-tutorial && npm init -y && touch index.js && mkdir utils && cd utils && touch utils.js utils.test.js && cd ..

For Windows users:

mkdir test-tutorial && cd test-tutorial && npm init -y && $null > index.js && mkdir utils && cd utils && $null > utils.js && $null > utils.test.js && cd ..

We will use Mocha in this tutorial for testing. You can check it out on mochajs.org. It’s easy and beginner friendly.

  1. Install Mocha like so:
install -D mocha

Note: We are using the -D flag in our npm install command to install Mocha as a dev-dependency (packages that are only needed during the development phase of your Node app). This is because we don’t really need to test at production (when our app or product is live).

Writing a Basic Test

Now that everything is set up, let’s write some code (as simple as possible) so that we can run tests against it. Let’s create some function in the utils/utils.js file like so:

module.exports.add = function (a, b) {
  return a + b
}
module.exports.square = function (a) {
  return a * a
}
module.exports.sqrt = function (a) {
  return Math.sqrt(a)
}

We are using module.exports to make it possible for us to use the functions in utils.js in index.js (or any other file that require(s) it).

Now, type this into your index.js file:

var utils = require(‘./utils/utils’)
console.log(utils.add(7,2))
console.log(utils.square(4))
console.log(utils.sqrt(16))

Then, modify the start script in your package.json,

“script”: {
  “start”: “node index.js”
}

to look like this:

{
  “name”: “test_tutorial”,
  “version”: “1.0.0”,
  “description”: “A tutorial to understand testing for nodejs”,
  “main”: “index.js”,
  “scripts”: {
    “start”:”node index.js”
  },
  “keywords”: [“NODE”, “JS”, “Test”],
  “author”: “Ajala Abdulsamii <kgasta@gmail.com>”,
  “license”: “MIT”,
  “devDependencies”: {
    “mocha”: “⁴.0.1”
  }
}

Then, run this in your terminal/cmd:

npm start

This runs ‘node index.js’ in the background (as specified in the package.json).

As you might expect, this prints 9, 16, and 4 respectively in the console when we run it.

Now, let's test our utils.js code and verify that it is working as expected.

We’ll write our test in the utils/utils.test.js like so:

// this imports the utils.js into our test file
var utils = require(‘./utils’)
// the ‘it’ syntax is a demonstration of what is referred to as ‘behavior driven development’
it(‘Should add two numbers’, function () {
  var res = utils.add(33,11);
  if (res !== 44) {
    throw new Error(‘Expected 44, but got ‘ + res + ‘.’);
  }
})
it(‘Should calculate square of a number’, function () {
  var res = utils.square(4);
  if (res !== 16) {
    throw new Error(‘Expected 16, but got ‘ + res + ‘.’);
  }
})
it(‘Should calculate the square root of a number’, function () {
  var res = utils.sqrt(4);
  if (res !== 16) {
    throw new Error(‘Expected 16, but got ‘ + res + ‘.’);
  }
})

In the code snippet above, we have written three test cases by writing our expectation of each function contained in the utils.js.

For every test case that passes, we see a check mark in the terminal/cmd. If they fail, we’ll see it indicated, as well as the error message specified in our test.

Now, modify your script in package.json by adding a test script to it like so:

“scripts”: {
 “start”:”node index.js”,
 “test”: “mocha **/*.test.js”
}

Technically, we are telling Mocha to run tests on any file that ends with ‘.test.js’ within our workspace.

Your package.json looks like this:

{
  “name”: “test_tutorial”,
  “version”: “1.0.0”,
  “description”: “”,
  “main”: “index.js”,
  “scripts”: {
    “start”:”node index.js”,
    “test”: “mocha **/*.test.js”
  },
  “keywords”: [],
  “author”: “”,
  “license”: “ISC”,
  “devDependencies”: {
    “mocha”: “^4.0.1”
  }
}

Now, run your test in terminal/cmd.

npm test

If you’ve been following along, you should get an output like this below in your terminal:

✓ Should add two numbers
✓ Should calculate square of a number
✓ Should calculate the square root of a number
3 passing (10ms)

Great! We have just successfully written our first test. That wasn’t so difficult, was it? (like GoTV).

Try distorting the functions in utils.js and running the test again (npm test).

You’ll notice that we keep writing if statements in our test cases. This doesn’t look good at all because we keep repeating ourselves, but I've made it easy to understand at first glance.

Now we’ll be using the expect library to run our assertions in our test cases. That and some other nifty stuff will come in the next part.

Recommendations

Check out this Medium article for a more robust explanation on testing! I hope this article has exposed you to how testing is done in JavaScript applications.

Discover and read more posts from Abdul-Samii Ajala
get started
post commentsBe the first to share your opinion
Voon Ming Hann
6 years ago

Testing is hard, how about testing real world application which the UI has many intractable pieces like drag and drop?

Abdul-Samii Ajala
6 years ago

Testing is not really hard if you know what tools and methods to use when testing. We shall be addressing scenarios and test cases like these in subsequent parts of this tutorial.

Show more replies