Writing Tests with Jest and Mocha in JavaScript

Testing is one of the most critical steps in the software development process to ensure the correctness and reliability of the code you write. In dynamic and rapidly changing languages like JavaScript, writing tests helps in early error detection and makes maintenance easier. In this article, we’ll walk you through how to write tests using popular testing frameworks Jest and Mocha, explaining each step and comparing the two.


1. What is Testing and Why is it Necessary?

A test is a piece of code written to verify whether the software works correctly. Tests serve several purposes in the software development process:

  • Error Detection: Identifying if there are any bugs in your code.
  • Improving Code Quality: Ensuring the software is stable and maintainable.
  • Guaranteeing Future Functionality: Ensuring that changes or new features don’t break existing code.

JavaScript is a dynamic language, making writing tests even more important. This allows you to verify whether different parts of your application are working as expected.


2. What is Jest and Mocha?

2.1. Jest

Jest is a popular testing framework developed by Facebook, especially used for testing React applications. Jest comes with many built-in features that make writing tests easy, including component-based testing, mocking, and snapshot testing.

Key features of Jest:

  • Easy Setup: Installing and using Jest is simple.
  • Built-in Mocking: Jest allows you to easily mock functions and modules.
  • Snapshot Testing: Useful for checking the output of React components.
  • Asynchronous Testing: You can easily write async/await or Promise-based tests.

2.2. Mocha

Mocha is a more flexible testing framework that works well with various assertion libraries. Mocha provides more freedom in how tests are written and allows integration with other tools. However, it is not as feature-rich as Jest in terms of built-in utilities.

Key features of Mocha:

  • Flexibility: Mocha provides high flexibility when writing tests.
  • Compatibility: Works well with different assertion libraries and tools.
  • Asynchronous Tests: Mocha uses a done callback function to handle asynchronous tests.

3. Writing Tests with Jest

Jest makes the process of writing tests simple with a user-friendly API, including test, expect, and beforeEach functions.

3.1. Setting Up Jest

First, you need to install Jest. Navigate to your project directory and run the following command:

npm install --save-dev jest

Next, add the test script in your package.json:

"scripts": {
  "test": "jest"
}

3.2. Writing Simple Tests with Jest

Let’s write a simple test for an addition function:

// math.js
function add(a, b) {
  return a + b;
}
module.exports = add;

Now, let's create a test file called math.test.js:

// math.test.js
const add = require('./math');

test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});
  • The test function takes the name of the test and the function to run the test.
  • The expect function checks if the given value matches the expected value.

Run the test using the following command:

npm test

3.3. Asynchronous Tests

Jest makes it easy to write asynchronous tests using async/await or Promises.

For example, let’s create an asynchronous function and test it:

// fetchData.js
const fetchData = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Data fetched');
    }, 2000);
  });
};

module.exports = fetchData;

Test:

// fetchData.test.js
const fetchData = require('./fetchData');

test('fetches data', async () => {
  const data = await fetchData();
  expect(data).toBe('Data fetched');
});

Jest automatically handles waiting for asynchronous operations to complete and checks the expected result.


4. Writing Tests with Mocha

Mocha is a more flexible testing framework compared to Jest. When writing tests in Mocha, you typically need to use assertion libraries like Chai.

4.1. Setting Up Mocha

To use Mocha and Chai, first install them in your project:

npm install --save-dev mocha chai

Next, add the test script in your package.json:

"scripts": {
  "test": "mocha"
}

4.2. Writing Simple Tests with Mocha

Let’s write a simple test for an addition function using Mocha and Chai:

// math.js
function add(a, b) {
  return a + b;
}
module.exports = add;

Test:

// math.test.js
const add = require('./math');
const chai = require('chai');
const expect = chai.expect;

describe('add function', () => {
  it('should add 1 + 2 to equal 3', () => {
    expect(add(1, 2)).to.equal(3);
  });
});
  • describe block is used to group your tests in a logical way.
  • it function defines an individual test case.
  • expect function is used to check if the value matches the expected result.

4.3. Asynchronous Tests

In Mocha, you use the done callback function to handle asynchronous tests.

// fetchData.js
const fetchData = (callback) => {
  setTimeout(() => {
    callback('Data fetched');
  }, 2000);
};

module.exports = fetchData;

Test:

// fetchData.test.js
const fetchData = require('./fetchData');
const chai = require('chai');
const expect = chai.expect;

describe('fetchData function', () => {
  it('should fetch data', (done) => {
    fetchData((data) => {
      expect(data).to.equal('Data fetched');
      done();
    });
  });
});

Here, the done callback notifies Mocha that the test is asynchronous and allows it to wait until the operation completes.


5. Jest vs Mocha: Which One Should You Use?

Advantages of Jest:

  • Built-in test, assertion, and mocking functions.
  • Optimized for React projects.
  • Snapshot testing and other advanced features.
  • Quick setup and configuration.

Advantages of Mocha:

  • High flexibility and modularity.
  • Works with various assertion libraries.
  • Larger testing community and resources.
  • More customization for complex projects.

When to Use Which Framework?

  • Jest: Ideal for those who need quick setup and ease of use, especially for React projects.
  • Mocha: Perfect for those who need more flexibility and customization for larger or more complex projects.

6. Conclusion

Jest and Mocha are powerful testing frameworks that make the process of writing tests in JavaScript easier. Jest is excellent for those looking for simplicity and quick setup, while Mocha offers more flexibility and customization. Both frameworks are great for writing asynchronous tests, mocking, and handling assertions.

Writing tests as early as possible helps ensure the reliability of your software. Depending on your project’s needs, you can choose the right testing framework to integrate into your development workflow.