DEV Community

DinmaOtutu
DinmaOtutu

Posted on

Unit Testing with Mocha: A Hands-On Tutorial For Beginners

Table of Contents

  1. Introduction
  2. What is Unit Testing?
  3. Why Mocha?
  4. Setting Up The Project
  5. Your First Test with Mocha
  6. Assertions in Mocha
  7. Hooks
  8. Testing Asynchronous Code
  9. Conclusion
  10. Further Reading

Introduction

Testing is an integral part of modern software development practices. Among various types of testing, unit testing is often the first line of defense against bugs and errors. In this tutorial, we will explore how to write unit tests using Mocha, a popular JavaScript testing framework.

What is Unit Testing?

Unit testing is the practice of testing the smallest pieces of code, usually individual functions or methods, in isolation from the rest of the codebase. The primary goals are:

  • Ensure code behaves as expected under various conditions.
  • Make it easier to refactor code.
  • Improve the overall design of the code.

Why Mocha?

Mocha is one of the most popular testing libraries for JavaScript and Node.js. Here are a few reasons why developers prefer Mocha:

  • Flexibility: Mocha is unopinionated about assertion libraries and lets you pair it with your choice like Chai, Jasmine, etc.
  • Rich Feature Set: Built-in test runners, test hooks, and reporters.
  • Ease of Use: Simple API makes it easy for beginners to pick up.

Setting Up The Project

Let's begin by setting up a new Node.js project and installing Mocha.

  1. Create a new directory for the project:

    mkdir mocha-tutorial
    cd mocha-tutorial
    
  2. Initialize a new Node.js project:

    npm init -y
    
  3. Install Mocha:

    npm install --save-dev mocha
    

Your First Test with Mocha

  1. Create a new file named math.js with the following function to test:

    function add(a, b) {
      return a + b;
    }
    
    module.exports = { add };
    
  2. Create another file named test.js:

    const { add } = require('./math');
    const assert = require('assert');
    
    describe('Math Functions', function() {
      it('should return 3 when 1 is added to 2', function() {
        assert.equal(add(1, 2), 3);
      });
    });
    
  3. Update your package.json:

    "scripts": {
      "test": "mocha test.js"
    },
    
  4. Run the test:

    npm test
    

If everything is set up correctly, you should see a passing test.

Assertions in Mocha

Mocha itself doesn't come with an assertion library, so you can pair it with any assertion library of your choice. In our example, we used Node's built-in assert.

assert.equal(add(1, 2), 3);
Enter fullscreen mode Exit fullscreen mode

Hooks

Mocha provides hooks like before(), after(), beforeEach(), and afterEach() for setup and teardown operations.

Example:

describe('Math Functions', function() {
  before(function() {
    // runs before all tests in this block
  });

  after(function() {
    // runs after all tests in this block
  });

  beforeEach(function() {
    // runs before each test in this block
  });

  afterEach(function() {
    // runs after each test in this block
  });
});
Enter fullscreen mode Exit fullscreen mode

Testing Asynchronous Code

Mocha makes it easy to test asynchronous code. Here's an example using promises:

Suppose you have an asynchronous addAsync function:

function addAsync(a, b) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(a + b), 100);
  });
}

module.exports = { addAsync };
Enter fullscreen mode Exit fullscreen mode

You can test it like so:

const { addAsync } = require('./math');
const assert = require('assert');

describe('Math Functions - Async', function() {
  it('should return 3 when 1 is added to 2 asynchronously', function() {
    return addAsync(1, 2).then(result => assert.equal(result, 3));
  });
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we've learned the basics of unit testing with Mocha. We've set up a simple project, written tests, explored assertions, and even delved into asynchronous testing. Mocha is a versatile and powerful framework that makes it easy to write tests for your JavaScript projects.

Further Reading

I hope you found this tutorial helpful. Happy testing!

Top comments (0)