0
0
NodejsHow-ToBeginner · 4 min read

How to Use Supertest for API Testing in Node.js

Use supertest by importing it and passing your Node.js app to it. Then chain HTTP methods like .get() or .post() with assertions such as .expect() to test your API endpoints easily.
📐

Syntax

The basic syntax of supertest involves importing the library, passing your Express app or server to it, and chaining HTTP methods with assertions.

  • request(app): Initializes the test with your app.
  • .get('/path'): Sends a GET request to the specified path.
  • .post('/path'): Sends a POST request.
  • .send(data): Sends JSON or other data in the request body.
  • .expect(statusCode): Checks the HTTP status code returned.
  • .expect('Content-Type', /json/): Checks response headers.
  • .end(callback): Optional callback to handle the response.
javascript
import request from 'supertest';
import app from './app';

request(app)
  .get('/api/example')
  .expect(200)
  .expect('Content-Type', /json/)
  .end((err, res) => {
    if (err) throw err;
    // further assertions
  });
💻

Example

This example shows how to test a simple Express API endpoint that returns JSON data. It uses supertest with jest to check the response status and body.

javascript
import express from 'express';
import request from 'supertest';

const app = express();

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

describe('GET /api/hello', () => {
  it('responds with json containing a greeting message', async () => {
    const response = await request(app)
      .get('/api/hello')
      .expect('Content-Type', /json/)
      .expect(200);

    expect(response.body).toEqual({ message: 'Hello, world!' });
  });
});
Output
PASS ./api.test.js GET /api/hello ✓ responds with json containing a greeting message (XX ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: XX s
⚠️

Common Pitfalls

Common mistakes when using supertest include:

  • Not returning or awaiting the request promise in async tests, causing tests to finish early.
  • Forgetting to import or properly initialize your app instance.
  • Using .end() without handling errors, which can hide test failures.
  • Not setting Content-Type headers when sending JSON data.

Always use async/await or return the supertest call in your test functions.

javascript
/* Wrong way: missing await or return */
test('GET /api fails silently', () => {
  return request(app)
    .get('/api/hello')
    .expect(200);
});

/* Right way: use async/await */
test('GET /api works', async () => {
  await request(app)
    .get('/api/hello')
    .expect(200);
});
📊

Quick Reference

MethodDescription
request(app)Initialize test with your app or server
.get(path)Send GET request to path
.post(path)Send POST request to path
.send(data)Send JSON or other data in request body
.expect(status)Assert HTTP status code
.expect(header, value)Assert response header
.end(callback)Handle response with callback (optional)

Key Takeaways

Import supertest and pass your Node.js app to start testing API endpoints.
Use async/await or return the supertest call to ensure tests run correctly.
Chain HTTP methods and assertions like .get(), .post(), and .expect() for clear tests.
Always check response status and content type to verify API behavior.
Handle errors properly to avoid silent test failures.