Unit Testing with Mocha: A Hands-On Tutorial For Beginners
Tags: mocha, testing, chai, unittesting
Published: 2023-09-04 09:34:30

---
title: Unit Testing with Mocha: A Hands-On Tutorial For Beginners
published: true
description: Understanding Mocha for beginners
tags: mocha, testing, chai, unittesting
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-09-04 09:31 +0000

---

## Table of Contents
1. [Introduction](#introduction)
2. [What is Unit Testing?](#what-is-unit-testing)
3. [Why Mocha?](#why-mocha)
4. [Setting Up The Project](#setting-up-the-project)
5. [Your First Test with Mocha](#your-first-test-with-mocha)
6. [Assertions in Mocha](#assertions-in-mocha)
7. [Hooks](#hooks)
8. [Testing Asynchronous Code](#testing-asynchronous-code)
9. [Conclusion](#conclusion)
10. [Further Reading](#further-reading)

---
## Introduction <a name="introduction"></a>

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? <a name="what-is-unit-testing"></a>

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? <a name="why-mocha"></a>

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 <a name="setting-up-the-project"></a>

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

1. Create a new directory for the project:

    ```bash
    mkdir mocha-tutorial
    cd mocha-tutorial
    ```

2. Initialize a new Node.js project:

    ```bash
    npm init -y
    ```

3. Install Mocha:

    ```bash
    npm install --save-dev mocha
    ```

## Your First Test with Mocha <a name="your-first-test-with-mocha"></a>

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

    ```javascript
    function add(a, b) {
      return a + b;
    }
    
    module.exports = { add };
    ```

2. Create another file named `test.js`:

    ```javascript
    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`:

    ```json
    "scripts": {
      "test": "mocha test.js"
    },
    ```

4. Run the test:

    ```bash
    npm test
    ```

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

## Assertions in Mocha <a name="assertions-in-mocha"></a>

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`.

```javascript
assert.equal(add(1, 2), 3);
```

## Hooks <a name="hooks"></a>

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

Example:

```javascript
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
  });
});
```

## Testing Asynchronous Code <a name="testing-asynchronous-code"></a>

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

Suppose you have an asynchronous `addAsync` function:

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

module.exports = { addAsync };
```

You can test it like so:

```javascript
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));
  });
});
```

## Conclusion <a name="conclusion"></a>

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 <a name="further-reading"></a>

- [Mocha Official Docs](https://mochajs.org/)
- [Chai Assertion Library](https://www.chaijs.com/)
- [Node.js Assert API](https://nodejs.org/api/assert.html)

I hope you found this tutorial helpful. Happy testing!