Skip to content

Latest commit

 

History

History
181 lines (133 loc) · 4.21 KB

File metadata and controls

181 lines (133 loc) · 4.21 KB

Topic 014: Test, build and deployment in Node.js

Topic 014: Test, build and deployment in Node.js

  • Using a testing framework in Node.js is essential for ensuring the reliability and quality of your code. One of the most popular testing frameworks for Node.js is Mocha, often used in conjunction with assertion libraries like Chai or Jest for a more comprehensive testing experience.

Here's a detailed explanation and example of how to use Mocha and Chai for testing in a Node.js application.

1. Setting Up Your Environment

First, you need to create a Node.js project if you haven't already. Initialize a new project using:

npm init -y

Then, install Mocha and Chai as development dependencies:

npm install --save-dev mocha chai

2. Project Structure

A common project structure for testing might look like this:

my-project/
│
├── src/
│   └── myModule.js
│
├── test/
│   └── myModule.test.js
│
├── package.json
└── node_modules/

3. Writing Code to Test

Let's say you have a simple module in src/myModule.js:

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

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add,
  subtract,
};

4. Writing Tests

Create a test file test/myModule.test.js where you'll write your test cases:

// test/myModule.test.js
const { expect } = require("chai");
const { add, subtract } = require("../src/myModule");

describe("myModule", () => {
  describe("add", () => {
    it("should add two numbers correctly", () => {
      const result = add(2, 3);
      expect(result).to.equal(5);
    });

    it("should return a negative number when summing a positive and a larger negative number", () => {
      const result = add(2, -3);
      expect(result).to.equal(-1);
    });
  });

  describe("subtract", () => {
    it("should subtract two numbers correctly", () => {
      const result = subtract(5, 3);
      expect(result).to.equal(2);
    });

    it("should return a negative number when the subtrahend is greater than the minuend", () => {
      const result = subtract(3, 5);
      expect(result).to.equal(-2);
    });
  });
});

5. Running Your Tests

To run your tests, add a test script to your package.json:

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

Then, run the tests using:

npm test

6. Interpreting Test Results

When you run npm test, Mocha will execute the test cases in test/myModule.test.js, and you'll see an output similar to this:

  myModule
    add
      ✓ should add two numbers correctly
      ✓ should return a negative number when summing a positive and a larger negative number
    subtract
      ✓ should subtract two numbers correctly
      ✓ should return a negative number when the subtrahend is greater than the minuend

  4 passing (20ms)

Each indicates a passing test case.

Additional Tips

  1. Before and After Hooks: Mocha provides hooks (before, after, beforeEach, afterEach) to set up preconditions and clean up after tests.

    before(() => {
      // Code to run before all tests
    });
    
    after(() => {
      // Code to run after all tests
    });
    
    beforeEach(() => {
      // Code to run before each test
    });
    
    afterEach(() => {
      // Code to run after each test
    });
  2. Async Tests: Mocha handles asynchronous tests as well. You can use async/await or return promises in your test functions.

    it("should resolve with the correct value", async () => {
      const result = await someAsyncFunction();
      expect(result).to.equal("expected value");
    });
  3. Coverage Reports: Integrate with Istanbul (via nyc) for coverage reports:

    npm install --save-dev nyc

    Add a coverage script:

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

    Run your tests with coverage:

    npm test
  • Using Mocha and Chai for testing in Node.js provides a robust and flexible framework for ensuring your code works as expected. By structuring your tests well and using the available hooks and features, you can maintain high-quality code and reduce bugs in your application.