Writing Unit Tests with Mocha and Chai in Node.js

 

Unit testing is an essential part of modern software development. It helps ensure that your code is working correctly, prevents bugs, and gives you confidence when making changes. In this guide, we’ll explore how to write unit tests in Node.js using Mocha and Chai.

Why Unit Testing Matters

Think of unit tests as a safety net. They help:

  • Catch bugs early in development
  • Improve code quality
  • Make refactoring easier
  • Increase confidence in your code

Prerequisites

Before we start, make sure you have:

  • Node.js installed
  • Mocha and Chai installed
  • A basic understanding of JavaScript

Step 1: Installing Mocha and Chai

First, initialize a Node.js project if you haven’t already:

npm init -y

Then install Mocha and Chai:

npm install --save-dev mocha chai

Step 2: Setting Up Mocha

Modify your package.json to add a test script:

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

Now, create a test directory and add a test file, e.g., test/math.test.js.

Step 3: Writing Your First Test

Let’s create a simple function to test. In math.js:

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

Now, write a test for it in test/math.test.js:

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

describe('Addition Function', function() {
    it('should return 5 when adding 2 and 3', function() {
        expect(add(2, 3)).to.equal(5);
    });
});

Run the test with:

npm test

If everything is correct, you should see a passing test!

Step 4: Using Chai Assertions

Chai provides multiple ways to assert values. Examples:

expect(5).to.equal(5); // Strict equality
expect([1, 2, 3]).to.have.lengthOf(3); // Array length
expect({ name: 'John' }).to.have.property('name'); // Object properties

Step 5: Testing Asynchronous Code

If your function returns a promise, use async/await:

async function fetchData() {
    return 'Hello World';
}

describe('Async Function', function() {
    it('should return Hello World', async function() {
        const data = await fetchData();
        expect(data).to.equal('Hello World');
    });
});

Step 6: Testing Errors

If you want to test if a function throws an error:

function throwError() {
    throw new Error('Something went wrong');
}

describe('Error Handling', function() {
    it('should throw an error', function() {
        expect(throwError).to.throw('Something went wrong');
    });
});

Conclusion

Unit testing with Mocha and Chai in Node.js is simple yet powerful. By writing tests, you ensure that your code works as expected and avoid nasty bugs. Now, go forth and test like a pro!

 

Post a Comment

0 Comments