Unit Testing in Node.js with Jest and Mocha

Unit testing is a crucial practice in modern software development that ensures individual components of your application function correctly in isolation. This article provides a practical guide on how to perform unit testing in a Node.js application. We will cover the setup, syntax, and execution of unit tests using two of the most popular testing frameworks in the JavaScript ecosystem: Jest and Mocha.

Setting Up a Sample Function to Test

Before writing tests, we need a simple JavaScript function to test. Create a file named math.js with the following code:

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

module.exports = { add };

Unit Testing with Jest

Jest is a complete, zero-configuration testing framework developed by Meta. It includes a test runner, assertion library, and mocking support out of the box.

1. Install Jest

To use Jest in your Node.js project, install it as a development dependency:

npm install --save-dev jest

Update your package.json to configure the test script:

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

2. Write a Jest Test

Create a test file named math.test.js. Jest automatically detects files ending in .test.js or .spec.js.

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

test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});

3. Run the Test

Execute the test suite using the npm command:

npm test

Unit Testing with Mocha and Chai

Mocha is a highly flexible test framework for Node.js. Unlike Jest, Mocha does not come with a built-in assertion library, so it is commonly paired with Chai.

1. Install Mocha and Chai

Install both Mocha and Chai as development dependencies:

npm install --save-dev mocha chai

Update your package.json to configure Mocha as your test runner:

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

2. Write a Mocha/Chai Test

Create a test file named math.spec.js. Mocha looks for a folder named test by default, or you can specify the files directly.

// math.spec.js
const { expect } = require('chai');
const { add } = require('./math');

describe('Math Functions', () => {
  it('should add 1 and 2 to equal 3', () => {
    expect(add(1, 2)).to.equal(3);
  });
});

3. Run the Test

Execute the Mocha test suite:

npm test

Key Differences to Consider