0
0
Expressframework~5 mins

Testing GET endpoints in Express

Choose your learning style9 modes available
Introduction

Testing GET endpoints helps you check if your server sends the right data when someone asks for it. It makes sure your app works as expected.

You want to check if your API returns the correct data for a user request.
You need to verify that your server handles errors properly when data is missing.
You want to confirm that your GET routes respond quickly and correctly after changes.
You are building a new feature and want to test the data your endpoint sends.
You want to automate tests to catch bugs early before users find them.
Syntax
Express
const request = require('supertest');
const app = require('./app');

describe('GET /endpoint', () => {
  it('should respond with status 200 and expected data', async () => {
    const response = await request(app).get('/endpoint');
    expect(response.status).toBe(200);
    expect(response.body).toEqual({ key: 'value' });
  });
});

Use supertest to simulate HTTP requests to your Express app.

Wrap tests inside describe and it blocks for clarity.

Examples
This test checks if the /hello route returns a 200 status and the text 'Hello World!'.
Express
const request = require('supertest');
const app = require('./app');

test('GET /hello returns greeting', async () => {
  const res = await request(app).get('/hello');
  expect(res.status).toBe(200);
  expect(res.text).toBe('Hello World!');
});
This test verifies that requesting user with id 123 returns the correct user data.
Express
const request = require('supertest');
const app = require('./app');

describe('GET /user/:id', () => {
  it('returns user data for valid id', async () => {
    const res = await request(app).get('/user/123');
    expect(res.status).toBe(200);
    expect(res.body).toHaveProperty('id', '123');
  });
});
Sample Program

This example creates a simple Express app with a GET route /greet. The test uses supertest to call this route and checks if the response status is 200 and the JSON message is correct.

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

const app = express();

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

describe('GET /greet endpoint', () => {
  it('should return greeting message with status 200', async () => {
    const response = await request(app).get('/greet');
    expect(response.status).toBe(200);
    expect(response.body).toEqual({ message: 'Hello, tester!' });
  });
});
OutputSuccess
Important Notes

Always test the status code and the response body to ensure your endpoint works correctly.

Use async/await to handle asynchronous requests cleanly in tests.

Run tests often to catch errors early during development.

Summary

Testing GET endpoints confirms your server sends the right data.

Use supertest with Express to simulate requests easily.

Check both status codes and response content in your tests.