Registry / testing / supertest

supertest

JSON →
library1.0jsnpmunverified

Supertest is an HTTP assertion library built on top of SuperAgent, designed for testing web applications and APIs in Node.js. It simplifies making HTTP requests to an application (or a raw http.Server instance) and asserting on the responses. Key features include automatically binding the server to an ephemeral port, chaining assertions for status codes, headers, and body content, and seamless integration with any JavaScript test framework. The current stable version is 7.2.2, with recent releases indicating an active maintenance schedule focused on bug fixes and dependency updates. It provides a high-level abstraction, allowing developers to write clear and concise HTTP tests while retaining the ability to leverage SuperAgent's lower-level API when needed. It is a fundamental tool for integration testing of Node.js web services, especially when using frameworks like Express or Koa.

npm install supertest
INSTALL
IMPORT
SIG · SUPERTEST
S
supertest
testingjavascriptv1.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

request
import request from 'supertest';
import { request } from 'supertest';
Supertest's primary export is a default function for making HTTP requests. Use a default import for ESM environments.
request
const request = require('supertest');
const { request } = require('supertest');
For CommonJS environments, the module directly exports the request function. No need to destructure or access a named property.
agent
import request from 'supertest'; const persistentAgent = request.agent();
import { agent } from 'supertest';
The `agent` method, used for persistent HTTP sessions (e.g., cookie management), is a property of the default `request` function, not a named export.

Demonstrates making GET and POST requests to an Express application, asserting on response status, headers, and body content using Supertest's fluent API without a formal test runner.

const request = require('supertest'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.get('/user', function(req, res) { res.status(200).json({ name: 'john', id: 1 }); }); app.post('/echo', function(req, res) { res.status(200).json({ received: req.body }); }); // Example test without a specific test framework (assertions via .end callback) request(app) .get('/user') .expect('Content-Type', /json/) .expect('Content-Length', '22') // Adjusted length for { name: 'john', id: 1 } (including spaces/quotes) .expect(200) .end(function(err, res) { if (err) { console.error('GET /user test failed:', err); } else if (res.body.name === 'john') { console.log('GET /user test passed.'); } else { console.error('GET /user test failed: Unexpected body.', res.body); } }); // Example with a POST request and chaining assertions request(app) .post('/echo') .send({ message: 'hello world' }) .expect('Content-Type', /json/) .expect(200) .end(function(err, res) { if (err) { console.error('POST /echo test failed:', err); } else if (res.body.received && res.body.received.message === 'hello world') { console.log('POST /echo test passed. Received:', res.body.received.message); } else { console.error('POST /echo test failed: Body not as expected.', res.body); } });
Debug
Known issues
breakingSupertest v7 dropped support for Node.js versions older than `14.16.0`. Projects running older Node.js versions must upgrade to at least 14.16.0 or newer to use Supertest v7.
fix
Upgrade your Node.js environment to version 14.16.0 or newer. Ensure your `package.json`'s `engines` field and CI/CD configurations reflect this change.
affects: >=7.0.0
gotchaWhen using the `.end(callback)` method, SuperAgent (and consequently Supertest) will pass any HTTP error (a response with a status code outside the 2xx range) as the first argument (`err`) to the callback, even if a `.expect(status)` assertion is not explicitly present. If `err` is not handled, tests might silently pass despite an HTTP error.
fix
Always include `.expect(status)` for expected success codes. Additionally, always check for and handle the `err` argument within your `.end()` callback, for example, `if (err) return done(err);` in test frameworks.
affects: >=1.0.0
gotchaAssertions made using `.expect()` within Supertest will not automatically throw an error if they fail when `.end(callback)` is used. Instead, the assertion failure is encapsulated as an error and passed to the `err` argument of the `.end()` callback. This means if `err` is not explicitly re-thrown or passed to your test framework's `done` callback, the test might incorrectly pass.
fix
Ensure that your `.end()` callback properly handles the `err` argument by either re-throwing it (`if (err) throw err;`) or by passing it to your test framework's `done` callback (`if (err) return done(err);`).
affects: >=1.0.0
breakingStarting from version 7.1.4, Supertest reverted an automatic server closing mechanism. This means that if you're testing an `http.Server` instance, it may no longer be automatically closed after tests complete, potentially leading to 'address already in use' errors or resource leaks in subsequent test runs.
fix
Manually ensure your test server is properly closed after tests. Implement a cleanup hook (e.g., `afterAll` or `afterEach` in Jest/Mocha) that calls `server.close()` on your `http.Server` instance.
affects: >=7.1.4
Errors
Common errors & fixes
Error: listen EADDRINUSE: address already in use :::[PORT]
An HTTP server from a previous test or process is still running on the same port, or your test setup is not properly closing the server after each test or suite.
fix
Ensure that any `http.Server` instance passed to `request()` is explicitly closed after your tests complete, typically in an `afterEach` or `afterAll` hook of your test runner using `server.close()`.
AssertionError: expected 200 'OK', got 404 'Not Found'
The requested API endpoint or path does not exist on the application under test, or the route handler is not correctly configured to respond to the specific HTTP method and path.
fix
Verify that the URL path and HTTP method (e.g., `.get('/user')`) exactly match a defined route in your application code. Double-check your application's route definitions and middleware application order.
Test passes unexpectedly even when an assertion (e.g., `.expect(500)`) should have failed.
The `err` argument within the `.end(callback)` function was not handled, causing the test runner to not register the assertion failure as a test failure.
fix
Within your `.end()` callback, ensure you explicitly handle any `err` argument. For example, in Mocha or Jest with `done` callback, use `if (err) return done(err);` or simply `if (err) throw err;` if using promises or async/await.
Upgrade
Version history
1.0latest on npm
Audit
Dependencies
superagentrequiredCore HTTP client library that Supertest builds upon for making requests.
Agent activity
11 hits · last 30 days
node
10
OpenAI (training)
1
Resources
supertest — npm install supertest · libregistry