Introduction to Unit Testing with Mocha & Chai

Introduction to Unit Testing with Mocha & Chai

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

Did you find this article valuable?

Support Victoria Lo by becoming a sponsor. Any amount is appreciated!

ย