Topic 014: Test, build and deployment in Node.js
Here’s a detailed explanation and example of how to use Mocha and Chai for testing in a Node.js application.
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
A common project structure for testing might look like this:
my-project/
│
├── src/
│ └── myModule.js
│
├── test/
│ └── myModule.test.js
│
├── package.json
└── node_modules/
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,
};
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);
});
});
});
To run your tests, add a test script to your package.json
:
"scripts": {
"test": "mocha"
}
Then, run the tests using:
npm test
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.
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
});
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");
});
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