← Back to list

What Is Testing and Why Is It Important?

Testing is the process of ensuring your code works as intended by validating its behavior under different scenarios. In software…

Rohit sutar · 2024-11-19 04:49 · 0 claps · 3.2 min read
#nodejs #backend-testing #jest #supertest #api-testing
Open on Medium ↗
Wiki topics: 🌐 · Web Development 💑 · Relationships

What Is Testing and Why Is It Important?

Testing is the process of ensuring your code works as intended by validating its behavior under different scenarios. In software development, tests help you:

  1. Catch Bugs Early: Identify and fix errors before they affect users.
  2. Ensure Stability: Confirm that changes or new features don’t break existing functionality.
  3. Save Time: Automated tests replace repetitive manual checks.
  4. Boost Confidence: Give you peace of mind that your app works correctly

How to Test in Node.js

Testing in Node.js is simple with tools like Jest and Supertest:

  1. Jest: A powerful testing framework for JavaScript applications. It comes with built-in utilities for writing, organizing, and running tests. Jest is fast, supports mocking, and works seamlessly with modern JavaScript frameworks.
  2. Supertest: A library for testing HTTP endpoints. It allows you to simulate HTTP requests and verify the responses, making it ideal for testing APIs.

Install Jest and Supertest:

Run this command to set up your project:

npm install --save-dev jest supertest

Testing an Express API in Node.js

Here’s how you can test an endpoint using Jest and Supertest:

Endpoint Code:

The /sum endpoint takes two numbers (a and b) from the request body, validates them, and returns their sum.

import express from "express";
import z from "zod";

const app = express();
app.use(express.json());

// Define the Zod schema for validating the input
const sumInput = z.object({
  a: z.number(), // `a` must be a number
  b: z.number(), // `b` must be a number
});

app.get("/sum", (req, res) => {
  // Validate the request body using the Zod schema
  const userInputs = sumInput.safeParse(req.body);

  // If validation fails, respond with status 411 and an error message
  if (!userInputs.success) {
    res.status(411).json({ message: "Invalid Inputs" });
  }

  // Extract validated input values
  const a = req.body.a;
  const b = req.body.b;

  res.json({ answer: a + b });
});

export { app };

Test Code:

Using Jest and Supertest, we validate both successful and error scenarios for the /sum endpoint.

import { describe, expect, it } from "@jest/globals";
import request from "supertest";
import { app } from "../app";

describe("Testing sum endpoint", () => {
  // Test case 1: Valid input should return the correct sum
  it("should return 2 + 2 equal to 4", async () => {
    // Use Supertest to make a GET request to the /sum endpoint
    const res = await request(app).get("/sum").send({ a: 2, b: 2 });

    // Assert that the response body contains the correct answer
    expect(res.body.answer).toBe(4);
  });

  // Test case 2: Invalid input should return an error message
  it("Should return error Invalid Input", async () => {
    // Use Supertest to make a GET request with invalid input data
    const res = await request(app).get("/sum").send({ a: "2", b: "2" });

    // Assert that the response body contains the error message
    expect(res.body.message).toBe("Invalid Inputs");
  });
});

How It Works:

  1. Valid Input: The test sends { a: 2, b: 2 } and expects a response of 4.
  2. Invalid Input: The test sends invalid data ({ a: "2", b: "2" }) and expects the error message "Invalid Inputs".

Running Tests

The test script runs all your tests using Jest, which is configured to look for files with names like *.test.js, *.spec.js, or files in a __tests__ folder.

// Package.json  

"scripts": {
    "test": "jest",
    "test:coverage": "jest --coverage",
    "dev": "nodemon --exec ts-node ./src/index.ts"
  },

Checking Test Coverage

The test:coverage script uses Jest's built-in coverage feature to analyze how much of your code is covered by your tests.

Command to Run:

npm run test:coverage

What It Does:

  • Runs all the tests in your project.
  • Generates a coverage report showing:
  • Statements Coverage: Percentage of code statements executed by tests.
  • Branch Coverage: How many if/else or conditional paths were executed.
  • Function Coverage: Percentage of functions that were tested.
  • Line Coverage: Percentage of code lines tested.
  • Outputs the results to the terminal and creates a coverage/ directory with detailed HTML reports.

Example of Test Coverage Report:

After running npm run test:coverage, you’ll see something like this:

 PASS  src/test/index.test.ts
  Testing sum endpoint                                                                                                                       
    √ should return 2 + 2 equal to 4 (54 ms)
    √ Should return error Invalid Input (11 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 | 
 app.ts   |     100 |      100 |     100 |     100 | 
----------|---------|----------|---------|---------|-------------------

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.304 s, estimated 3 s
Ran all test suites.
Done in 2.97s.

Conclusion

Testing is an essential part of writing reliable, maintainable code. With Jest and Supertest, you can easily test your Node.js applications by validating APIs and catching errors before they reach users. Whether you’re building a small project or a complex system,


메타데이터
post_id
fc06309fb565
slug
what-is-testing-and-why-is-it-important-fc06309fb565
url
https://medium.com/@rohitsutar082/what-is-testing-and-why-is-it-important-fc06309fb565
canonical_url
https://medium.com/@rohitsutar082/what-is-testing-and-why-is-it-important-fc06309fb565
author_url
https://medium.com/@rohitsutar082
status
ok
fetched_at
2026-06-09 15:37:30