Bird
Raised Fist0
Expressframework~10 mins

Supertest for HTTP assertions in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Supertest for HTTP assertions
Write Express app
↓
Import Supertest
↓
Create test request
↓
Send HTTP request
↓
Receive response
↓
Assert response status and body
↓
Test passes or fails
This flow shows how Supertest sends HTTP requests to an Express app and checks the responses step-by-step.
Execution Sample
Express
const request = require('supertest');
const express = require('express');
const app = express();
app.get('/hello', (req, res) => res.send('Hi!'));

request(app).get('/hello').expect(200).expect('Hi!').end();
This code creates a simple Express app and uses Supertest to check that GET /hello returns status 200 and body 'Hi!'.
Execution Table
StepActionRequest Method & URLResponse StatusResponse BodyAssertion Result
1Create Express app----
2Define GET /hello route----
3Supertest sends GET requestGET /helloPendingPendingPending
4Express app receives requestGET /hello---
5App sends responseGET /hello200Hi!-
6Supertest checks statusGET /hello200Hi!Pass
7Supertest checks bodyGET /hello200Hi!Pass
8Test ends---Pass
💡 Test ends after all assertions pass or fail
Variable Tracker
VariableStartAfter Step 3After Step 5Final
requestundefinedSupertest request objectSupertest response objectTest result (pass)
appExpress app instanceExpress app instanceExpress app instanceExpress app instance
Key Moments - 3 Insights
Why does Supertest need the Express app instance?
Supertest uses the app instance to send HTTP requests directly without starting a server, as shown in execution_table step 3.
What happens if the response status is not what we expect?
Supertest will mark the assertion as failed at step 6, stopping the test or reporting failure.
Can Supertest check response headers too?
Yes, you can add .expect('header-name', 'value') to check headers, similar to how body and status are checked in steps 6 and 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response body at step 5?
A"Hello"
B"Hi!"
CEmpty string
DUndefined
💡 Hint
Check the 'Response Body' column at step 5 in the execution_table.
At which step does Supertest verify the HTTP status code?
AStep 4
BStep 3
CStep 6
DStep 7
💡 Hint
Look at the 'Assertion Result' column for status check in execution_table.
If the app returned status 404 instead of 200, what would happen in the execution table?
AStep 6 assertion would fail
BStep 5 response status would be 200
CTest would pass anyway
DStep 3 request would change
💡 Hint
Refer to the 'Response Status' and 'Assertion Result' columns in execution_table.
Concept Snapshot
Supertest lets you test Express apps by sending HTTP requests directly.
Use request(app).get('/path').expect(status).expect(body) to check responses.
No need to start a server; Supertest handles it internally.
Assertions stop the test if they fail.
You can chain multiple .expect() calls for status, body, headers.
Full Transcript
Supertest is a tool to test Express HTTP servers easily. You write your Express app code, then use Supertest to send HTTP requests to it without starting a real server. The flow starts by creating the app, then Supertest sends a request like GET /hello. The app receives it and sends back a response. Supertest checks the response status and body against what you expect. If all checks pass, the test passes. If any check fails, the test fails. Variables like the request object and app instance change as the test runs. Common confusions include why the app instance is needed (to send requests directly), what happens on assertion failure (test fails immediately), and that Supertest can check headers too. The execution table shows each step from sending the request to checking the response. This helps beginners see how the test runs step-by-step.

Practice

(1/5)
1. What is the main purpose of using Supertest in Express applications?
easy
A. To create database connections automatically
B. To send fake HTTP requests and check server responses
C. To deploy the Express app to production
D. To style the Express server pages

Solution

  1. Step 1: Understand Supertest's role

    Supertest is a tool used to simulate HTTP requests to your Express server without needing a browser.
  2. Step 2: Identify its main use

    It helps test server responses like status codes and data returned, ensuring your server works as expected.
  3. Final Answer:

    To send fake HTTP requests and check server responses -> Option B
  4. Quick Check:

    Supertest = fake HTTP requests and response checks [OK]
Hint: Supertest sends fake requests to test server responses [OK]
Common Mistakes:
  • Thinking Supertest styles pages
  • Confusing Supertest with deployment tools
  • Assuming it manages databases
2. Which of the following is the correct way to import Supertest in a Node.js Express test file?
easy
A. import request from 'supertest';
B. const supertest = import('supertest');
C. const request = require('supertest');
D. require('supertest').request;

Solution

  1. Step 1: Identify import syntax

    In Node.js, the most common way to import Supertest is using CommonJS syntax: const request = require('supertest');.
  2. Step 2: Check other options

    import request from 'supertest'; uses ES module syntax which requires specific setup and may not work by default. const supertest = import('supertest'); uses invalid syntax. require('supertest').request; accesses a non-existent property.
  3. Final Answer:

    const request = require('supertest'); -> Option C
  4. Quick Check:

    CommonJS require syntax = const request = require('supertest'); [OK]
Hint: Use CommonJS require syntax for Supertest in Node.js [OK]
Common Mistakes:
  • Using ES module import without setup
  • Trying to destructure or access wrong properties
  • Using invalid import syntax
3. Given the following test code, what will be the status code of the response?
import request from 'supertest';
import express from 'express';

const app = express();
app.get('/hello', (req, res) => res.status(200).send('Hi'));

test('GET /hello returns status 200', async () => {
  const response = await request(app).get('/hello');
  expect(response.status).toBe(201);
});
medium
A. 200
B. 404
C. 201
D. 500

Solution

  1. Step 1: Analyze the Express route

    The route /hello sends a response with status code 200 and body 'Hi'.
  2. Step 2: Check the test assertion

    The test expects status 201, but the actual response status is 200, so the test will fail if expecting 201.
  3. Final Answer:

    200 -> Option A
  4. Quick Check:

    Route sends 200, test expects 201, actual = 200 [OK]
Hint: Match expected status with route's actual status code [OK]
Common Mistakes:
  • Confusing expected and actual status codes
  • Assuming 201 is default success code
  • Ignoring route's explicit status
4. Identify the error in this Supertest test code snippet:
import request from 'supertest';
import app from './app';

test('POST /data returns 201', async () => {
  const res = await request(app).post('/data')
    .send({ name: 'Alice' })
    .expect(201);
  expect(res.body.name).toBe('Alice');
});
medium
A. No error, code is correct
B. Missing await before request call
C. Using .expect() and then checking res.body without await
D. POST method should not have a body

Solution

  1. Step 1: Review async/await usage

    The await is correctly used before request(app).post(...), so the promise resolves before assertions.
  2. Step 2: Check .expect and body assertions

    Using .expect(201) is valid and chaining expect(res.body.name).toBe('Alice') is correct after awaiting the response.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    Await + .expect + body check = correct usage [OK]
Hint: Await the request before assertions to avoid errors [OK]
Common Mistakes:
  • Forgetting await causing unresolved promises
  • Misusing .expect without awaiting
  • Assuming POST cannot have a body
5. You want to test an Express route that returns JSON only if a query parameter type=admin is present, otherwise it returns 403 Forbidden. Which Supertest code snippet correctly tests the 403 response when the query parameter is missing?
hard
A. await request(app).get('/secret').query({ type: 'user' }).expect(403);
B. await request(app).get('/secret?type=admin').expect(403);
C. await request(app).post('/secret').send({ type: 'admin' }).expect(403);
D. await request(app).get('/secret').expect(403);

Solution

  1. Step 1: Understand route behavior

    The route returns JSON only if query type=admin is present; otherwise, it returns 403 Forbidden.
  2. Step 2: Identify test for missing query parameter

    To test 403 when the parameter is missing, send a GET request without any query parameters.
  3. Step 3: Evaluate options

    await request(app).get('/secret').expect(403); sends GET without query, expecting 403, which matches the requirement. await request(app).get('/secret').query({ type: 'user' }).expect(403); sends type=user, which is not missing but wrong type, so may or may not return 403 depending on implementation. await request(app).post('/secret').send({ type: 'admin' }).expect(403); uses POST instead of GET. await request(app).get('/secret?type=admin').expect(403); sends type=admin which should return success, not 403.
  4. Final Answer:

    await request(app).get('/secret').expect(403); -> Option D
  5. Quick Check:

    Missing query param = GET without query = expect 403 [OK]
Hint: Test missing query by omitting .query() in GET request [OK]
Common Mistakes:
  • Sending wrong HTTP method (POST instead of GET)
  • Including wrong query parameters instead of missing
  • Expecting 403 when query param is present
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard