0
0
Expressframework~5 mins

Why testing APIs matters in Express

Choose your learning style9 modes available
Introduction

Testing APIs helps make sure your app talks correctly with other apps. It finds problems early so users get a smooth experience.

When you build a new API endpoint to share data with other apps.
When you update your API and want to check nothing broke.
When you want to confirm your API handles errors properly.
When you want to automate checks so your API stays reliable.
When you want to test how your API works under different conditions.
Syntax
Express
const request = require('supertest');
const app = require('./app');

describe('GET /api/data', () => {
  it('should return data with status 200', async () => {
    const response = await request(app).get('/api/data');
    expect(response.statusCode).toBe(200);
    expect(response.body).toHaveProperty('data');
  });
});

This example uses supertest to test an Express API.

Tests check the status code and response body.

Examples
Simple GET request test checking for status 200.
Express
request(app).get('/api/users').expect(200).then(response => {
  console.log(response.body);
});
POST request test sending login data and expecting success.
Express
request(app).post('/api/login').send({ username: 'user', password: 'pass' }).expect(200);
Test for a missing item expecting a 404 error.
Express
request(app).get('/api/items/123').expect(404);
Sample Program

This Express app has one API endpoint /api/hello that returns a greeting message in JSON.

The test checks if the endpoint returns status 200 and the correct message.

We run the test manually and print results to the console.

Express
const express = require('express');
const request = require('supertest');

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

app.get('/api/hello', (req, res) => {
  res.json({ message: 'Hello, world!' });
});

// Manual test with supertest
(async () => {
  const response = await request(app)
    .get('/api/hello')
    .expect(200)
    .expect({ message: 'Hello, world!' });
  console.log(response.statusCode);
  console.log(response.body);
})();
OutputSuccess
Important Notes

Testing APIs early helps catch bugs before users see them.

Automated tests save time by running checks quickly and often.

Use tools like supertest with Express for easy API testing.

Summary

Testing APIs ensures your app works well with others.

It helps find and fix problems early.

Automated API tests make your development faster and safer.