CodeBlanks Logo Icon CodeBlanks

Supertest

Learn HTTP testing with supertest.

Supertest

Supertest is a library that lets you test Express applications without making real HTTP requests. It invokes the app in memory; it does not open a real port. This makes tests fast and isolated.

Example: const request = require("supertest"); const app = require("./app"); request(app).get("/users").expect(200);. This sends a GET /users request to app in memory and expects the response to be 200. Supertest skips Express's app.listen; instead it calls http.createServer(app) directly. So the app.listen code is not invoked for tests. Supertest's chain structure lets you write readable tests: request(app).get("/").expect(200).expect("Content-Type", /json/).

The chain test structure

Supertest's power is in its chain structure. request(app).get(path).expect(status) sends the request and verifies the response status in a single line. Multiple .expect calls can also be chained.

Example: request(app).post("/users").send({ name: "Ayşe" }).expect(201).expect("Content-Type", /json/);. This sends a POST /users request with the body { name: "Ayşe" }; it expects the response to be 201 and to have a JSON content type. .send sets the body, .expect does the assertion. The chain improves the readability of the test. If multiple assertions are chained, all must pass; if any fails, the test fails. So each test should focus on a single behavior.

Practice Write a GET test with supertest

Import the supertest module with require. Import app with require("./app"). After const request = require("supertest"), print "supertest ready" with console.log.

Starter code

index.js
// Import supertest and app
// write here

// Print "supertest ready"
// write here

Sample solution

index.js
const request = require("supertest");
const app = require("./app");
console.log("supertest ready");

Expected output

supertest ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the request call

Question
const request = require(____);
Answer
const request = require("supertest");

Explanation: The supertest module is loaded as "supertest".

2 Match each method to its role

Term Meaning
request(app) Starts a request
.get/.post Sets the HTTP method
.send Adds a body
.expect Does an assertion

3 Why doesn't supertest open a real port?

index.js
request(app).get('/users')
  • Because tests are slow
  • Because Express doesn't run
  • Because it skips app.listen
  • Because it invokes app in memory Correct answer

Explanation: Supertest invokes app in memory.

All lessons in Advanced