Node.js Testing

Here is a complete and beginner-friendly guide on Node.js Testing, covering all essential topics: unit testing, integration testing, API testing, mocking, popular frameworks, and real examples.


🚀 Node.js Testing – Complete Guide

Testing ensures reliability, prevents bugs, and keeps your Node.js application maintainable.
Node.js supports several testing tools and methodologies.


📌 1. Types of Testing in Node.js

Unit Testing

Tests small, independent functions.

Integration Testing

Tests modules working together (e.g., API + Database).

End-to-End (E2E) Testing

Simulates real user workflow.

API Testing

Check REST APIs (status code, response, errors).

Mocking & Stubbing

Replace real services with fake ones.


📌 2. Popular Node.js Testing Frameworks

ToolPurpose
JestEasiest + Most Popular
MochaFlexible + Widely used
ChaiAssertion library
SupertestAPI testing
SinonMocking, spying, stubs
JasmineBDD testing

👉 Best choice for beginners: Jest + Supertest


📌 3. Installing Jest

npm install --save-dev jest

Add script in package.json:

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

📌 4. Unit Test Example (with Jest)

📁 math.js

function add(a, b) {
return a + b;
}

module.exports = add;

📁 math.test.js

const add = require("./math");

test("adds two numbers", () => {
expect(add(5, 7)).toBe(12);
});

Run test:

npm test

📌 5. Testing Asynchronous Code

Example using async/await:

📁 fetchUser.js

async function fetchUser() {
return { id: 1, name: "Vipul" };
}

module.exports = fetchUser;

📁 fetchUser.test.js

const fetchUser = require("./fetchUser");

test("fetch user returns object", async () => {
const user = await fetchUser();
expect(user.name).toBe("Vipul");
});


📌 6. Mocking (Fake functions)

Mocking helps isolate code and remove dependency on real services.

Example using Jest mock:

const db = {
getUser: jest.fn(() => ({ id: 1, name: "Test" }))
};

test("mock database call", () => {
expect(db.getUser()).toEqual({ id: 1, name: "Test" });
});


📌 7. Testing Node.js APIs (Supertest)

Install Supertest:

npm install --save-dev supertest
npm install express

📁 app.js (Simple API)

const express = require("express");
const app = express();

app.get("/hello", (req, res) => {
res.json({ message: "Hello World" });
});

module.exports = app;

📁 app.test.js (API Test)

const request = require("supertest");
const app = require("./app");

test("GET /hello", async () => {
const res = await request(app).get("/hello");
expect(res.status).toBe(200);
expect(res.body.message).toBe("Hello World");
});

Run:

npm test

📌 8. Integration Testing with Database

Example: Mocking MongoDB database using mongodb-memory-server for testing.

Install:

npm install --save-dev mongodb-memory-server

Now your tests run without touching real database.


📌 9. Snapshot Testing (Jest)

Great for testing large JSON responses (API output).

expect(response.body).toMatchSnapshot();

📌 10. Code Coverage

Get test coverage:

npm test -- --coverage

Shows:

  • lines covered

  • branches

  • functions

  • statements


📌 11. Best Practices for Node.js Testing

✔ Test small pieces of code
✔ Use mocks for database, external APIs
✔ Write tests along with code (TDD)
✔ Keep tests independent
✔ Name tests clearly
✔ Include negative cases (errors, invalid inputs)


📌 12. Folder Structure

project/

├─ src/
│ ├─ controllers/
│ ├─ routes/
│ ├─ services/

├─ tests/
│ ├─ unit/
│ ├─ integration/

└─ package.json

You may also like...