Unit, Integration, and Mocking - Textnotes

Unit, Integration, and Mocking


Learn how to test TypeScript applications effectively. This module explains unit testing, integration testing, and mocking strategies to ensure robust, reliable, and maintainable code

1. Unit Testing

Unit tests verify individual functions, classes, or components in isolation.

Setup with Jest


npm install --save-dev jest ts-jest @types/jest
npx ts-jest config:init

Example Unit Test


// sum.ts
export const sum = (a: number, b: number) => a + b;

// sum.test.ts
import { sum } from "./sum";

test("adds 2 + 3 to equal 5", () => {
expect(sum(2, 3)).toBe(5);
});

Unit testing ensures that individual units of code work as expected.

2. Integration Testing

Integration tests verify the interaction between multiple modules or components.

Example with Express


import request from "supertest";
import express from "express";

const app = express();
app.get("/hello", (req, res) => res.send("Hello, Muni"));

test("GET /hello returns Hello, Muni", async () => {
const response = await request(app).get("/hello");
expect(response.text).toBe("Hello, Muni");
expect(response.status).toBe(200);
});

Integration tests ensure different parts of the application work together correctly.

3. Mocking and Coverage

Mocking simulates dependencies to isolate code for testing, while coverage measures how much of the code is tested.

Example: Mocking a Module


jest.mock("./sum", () => ({
sum: jest.fn(() => 10),
}));

import { sum } from "./sum";

test("mock sum function", () => {
expect(sum(2, 3)).toBe(10);
});

Checking Coverage


npx jest --coverage

Coverage reports show which lines, functions, and branches are tested, helping improve test quality.

Conclusion

Testing TypeScript applications with unit tests, integration tests, and mocking improves code reliability and maintainability. Proper testing ensures early bug detection, type-safe verification, and confidence in application behavior.