Introduction to Unit Testing with Mocha & Chai

Subscribe to my newsletter and never miss my upcoming articles

Today's post title sounds extremely delicious isn't it? But Mocha and Chai are not beverages, they are a JavaScript test framework and assertion library used for testing!

Testing is an essential part of development. If you haven't read it already, please check out my post on Automated Testing with Node.js where I cover the basic testing processes in JavaScript and discuss why it is important for quality assurance.

This time, I'll introduce a new type of testing called Unit Testing.

Unit Testing

Testing whether an individual part of an app like a function or method is fit for use. A unit can be defined as the smallest testable part of an app. Developers perform unit testing to make sure that a unit, on its own, can perform what it is intended to do without affecting other areas of the code.

As your code gets more complex with new functions, dependencies and classes, it is important to have unit testing in your app to test if any of the new code is creating bugs in the app. This makes it more efficient to detect bugs and errors in your code.

In JavaScript, we can use Mocha and Chai to write unit test cases.

Mocha and Chai

Mocha is a test framework which you can use to run tests. Chai is an assertion library which gives us descriptive and easy-to-read syntax for our test assertions.

In unit testing, assertion refers to the process of confirming the output of the function/test to be exactly the same as the intended output.

Step 1: Download Node.js and npm

Download Node.js (with npm) at: https://nodejs.org/en/download/

After it is installed, to check if it is there, go to your command prompt:

node -v
npm -v

Step 2: Install Mocha

To test on our browser we run the following in our project file:

npm install mocha chai --save-dev

A folder called node_modules should appear in your project.

Step 3: Create a Test Page

Let's first create a test page where we can see the results of the tests.

<!DOCTYPE html>
<html>
  <head>
    <title>Unit Testing Tutorial</title>
    <link rel="stylesheet" href="node_modules/mocha/mocha.css">
  </head>
  <body>
    <div id="mocha"></div>
    <script src="node_modules/mocha/mocha.js"></script>
    <script src="node_modules/chai/chai.js"></script>
    <script>mocha.setup('bdd')</script>

    <!-- Test code here -->

    <script>
      mocha.run();
    </script>
  </body>
</html>

As you can see in the code, we are using Mocha's own CSS to style the page and loading mocha.js and chai.js <script> into the page. Then we call the mocha.setup('bdd') to load its BDD (Behavior Driven Development) interface.

BDD is a technique which describes a function, explains what it does and uses test case(s) to assert that it works as intended.

Below the setup, we shall write our test code below and finally, we will run mocha with the <script> mocha.run().

Step 4: Create a Test Folder

To keep the tests code organized, we shall put all tests files in a separate directory by creating a /tests folder in our project's root directory.

Later, we can place all our test files (i.e. testFunction1.js, testModule1.js) inside the /tests folder.

Step 5: A Sample Test

Let's create a sample test. Start by creating a sumTest.js in your /tests folder and create a test:

var assert = chai.assert;

describe("sum", function() {
  it("adds numbers", function() {
       assert.equal(sum(6, 3), 9);
  });
});

This test is a simple example of BDD technique:

  • First we describe the function. It is called 'sum'.
  • Next we explain what it does. In the sum function's case, it adds numbers.
  • Finally, we give a test case using assert.equal() where the first parameter is the function and the second is the expected output of the function.

Step 6: The Sum Function

So we have created our test. But we haven't created our sum function. If we run the test now, it will give errors. Let's create a sum.js in our root directory with the code:

function sum(num1, num2){
    return num1 + num2;
}

Great! Now let's run our test.

Run Test

Start by adding our sumTest.js and sum.js to our HTML page. It should look like:

<!DOCTYPE html>
<html>
  <head>
    <title>Unit Testing Tutorial</title>
    <link rel="stylesheet" href="node_modules/mocha/mocha.css">
  </head>
  <body>
    <div id="mocha"></div>
    <script src="node_modules/mocha/mocha.js"></script>
    <script src="node_modules/chai/chai.js"></script>
    <script>mocha.setup('bdd')</script>

    <script src="sum.js"></script>

    <script src="tests/sumTest.js"></script>

    <script>
      mocha.run();
    </script>
  </body>
</html>

And now, if we run our testPage.html in our browser, it should look like:

1.PNG

Yay! We passed the test! That means our function should be as we intended.

Note: In practice, there are many cases where the function may be incorrect but tests are passed. A proper way to deal with this is understanding what the function is supposed to do and testing for that specific use.

That's all for today!

With unit testing, there's more you can do with Mocha and Chai! This simple example is not a good way to test a function. Usually, there would be more 'it' and 'assert' statements to check for various conditions the function has to meet in order to work as it intended. I would recommend making your own tests in your projects to learn how to design tests that can effectively detect flaws/errors in a code.

Some readings to get started with:

Thanks for reading! Please share any comments or questions below and good luck with unit testing! Cheers!

No Comments Yet