Node.js
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.
Exercise 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.
Show example solution
const request = require("supertest");
const app = require("./app");
console.log("supertest ready");
Test yourself
-
Complete the request call
const request = require(____);
Show answer
const request = require("supertest");
-
Match each method to its role
- request(app)
- Starts a request
- .get/.post
- Sets the HTTP method
- .send
- Adds a body
- .expect
- Does an assertion
-
Why doesn't supertest open a real port?
request(app).get('/users')
- Because tests are slow
- Because Express doesn't run
- Because it skips app.listen
- Because it invokes app in memory
Show answer
Because it invokes app in memory — Supertest invokes app in memory.
Next lesson: Test database