Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Unit Testing in Node.js (e.g., Mocha, Chai)

Unit Testing in Node.js (e.g., Mocha, Chai)

Unit testing is a fundamental practice in software development that involves testing individual units or components of your code in isolation to ensure they work as expected. In Node.js, you can perform unit testing using various testing frameworks and assertion libraries. In this example, I'll demonstrate unit testing with Mocha and Chai, which are popular choices for testing Node.js applications.

Step 1: Set Up Your Project

1. Create a new directory for your Node.js project and navigate into it:

mkdir my-nodejs-project
cd my-nodejs-project
 

2. Initialize your project with npm:

npm init -y
 

3. Install Mocha and Chai as development dependencies:


npm install mocha chai --save-dev

 

Step 2: Write Your Code

Let's create a simple JavaScript module that we want to test. Create a file named math.js with the following content:

// math.js
module.exports = {
  add: (a, b) => a + b,
  subtract: (a, b) => a - b,
  multiply: (a, b) => a * b,
  divide: (a, b) => (b === 0 ? 'Cannot divide by zero' : a / b),
};

 

Step 3: Write Unit Tests

Create a directory named test to store your test files:

mkdir test
 

Inside the test directory, create a file named math.test.js to write your unit tests using Mocha and Chai:

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

describe('Math Operations', () => {
  it('should add two numbers', () => {
    expect(math.add(2, 3)).to.equal(5);
  });

  it('should subtract two numbers', () => {
    expect(math.subtract(5, 3)).to.equal(2);
  });

  it('should multiply two numbers', () => {
    expect(math.multiply(2, 3)).to.equal(6);
  });

  it('should divide two numbers', () => {
    expect(math.divide(6, 3)).to.equal(2);
  });

  it('should handle division by zero', () => {
    expect(math.divide(6, 0)).to.equal('Cannot divide by zero');
  });
});
 

Step 4: Configure Mocha

In your package.json file, add a test script to run Mocha:

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

Step 5: Run the Tests

Now, you can run your unit tests using the following command:

npm test
 

Mocha will discover and run the tests in the test directory, and Chai's assertions will verify the expected outcomes.