SuperAgent driven library for testing HTTP servers with fluent assertions and automatic server binding to ephemeral ports
npx @tessl/cli install tessl/npm-supertest@7.1.0SuperTest is a powerful HTTP testing library built on top of SuperAgent that provides a high-level abstraction for testing HTTP servers, applications, and APIs. It automatically handles server binding to ephemeral ports, provides fluent assertion APIs for status codes, headers, and response bodies, and integrates seamlessly with popular testing frameworks like Mocha.
npm install supertest --save-devconst request = require('supertest');For ES modules:
import request from 'supertest';You can also import specific classes and functions:
const { Test, agent } = require('supertest');const request = require('supertest');
const express = require('express');
const app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'john' });
});
// Test the app
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});SuperTest is built around several key components:
The main entry point creates test request objects for different HTTP methods.
/**
* Test against the given app, returning an object with HTTP method functions
* @param {Function|Server|String} app - Express app, HTTP server, or URL string
* @param {Object} options - Configuration options including http2 support
* @returns {Object} Object with HTTP method functions (get, post, put, delete, etc.)
*/
function request(app, options = {}) {}HTTP Method Functions (dynamically created):
// Standard HTTP methods available on request object
get(url) // Returns Test instance for GET request
post(url) // Returns Test instance for POST request
put(url) // Returns Test instance for PUT request
delete(url) // Returns Test instance for DELETE request
patch(url) // Returns Test instance for PATCH request
head(url) // Returns Test instance for HEAD request
options(url) // Returns Test instance for OPTIONS request
// ... all other standard HTTP methods
del(url) // Alias for delete() method for backward compatibilityHTTP/2 Support:
// Enable HTTP/2 protocol
request(app, { http2: true })
.get('/user')
.expect(200);Core assertion functionality for validating HTTP responses.
/**
* Test class extending SuperAgent Request with assertion capabilities
*/
class Test {
/**
* Chain assertions for HTTP responses with multiple overloads
* @param {Number|Array|String|RegExp|Function|Object} a - Status code, body, header name, or custom function
* @param {String|Number|RegExp|Function} b - Header value or callback
* @param {Function} c - Optional callback
* @returns {Test} Test instance for chaining
*/
expect(a, b, c) {}
/**
* Execute the request and run assertions
* @param {Function} fn - Optional callback (err, res) => {}
* @returns {Test} Test instance
*/
end(fn) {}
/**
* Set Authorization Bearer token header
* @param {String} token - Bearer token value
* @returns {Test} Test instance for chaining
*/
bearer(token) {}
}Assertion Examples:
// Status code assertions
.expect(200)
.expect(404)
.expect([200, 404]) // Multiple acceptable status codes
// Body assertions
.expect('Some text')
.expect({ key: 'value' })
.expect(/regex pattern/)
// Header assertions
.expect('Content-Type', 'application/json')
.expect('Content-Type', /json/)
// Custom assertion functions
.expect(function(res) {
if (res.body.items.length !== 3) {
throw new Error('Expected 3 items');
}
})
// Combining assertions with callbacks
.expect(200, function(err, res) {
if (err) throw err;
})Agent functionality for maintaining sessions across multiple requests.
/**
* TestAgent class for persistent HTTP sessions with cookie management
* @param {Function|Server} app - Express app or HTTP server
* @param {Object} options - Configuration options including http2 support
* @returns {TestAgent} Agent instance
*/
function agent(app, options = {}) {}
class TestAgent {
/**
* Set host header for all requests
* @param {String} host - Host header value
* @returns {TestAgent} Agent instance for chaining
*/
host(host) {}
// All HTTP method functions available (same as main request function)
get(url, fn) {} // Returns Test instance with agent context
post(url, fn) {} // Returns Test instance with agent context
// ... all other HTTP methods
del(url, fn) {} // Alias for delete method
}Session Usage:
const request = require('supertest');
const app = require('./app');
// Create persistent agent
const agent = request.agent(app);
// Login and get session cookie
agent
.post('/login')
.send({ username: 'user', password: 'pass' })
.expect(200)
.end(function(err, res) {
if (err) throw err;
// Use the same agent for authenticated requests
agent
.get('/profile')
.expect(200)
.end(function(err, res) {
// Session cookie automatically included
});
});Convenient method for setting Authorization Bearer tokens.
/**
* Set Authorization Bearer token header
* @param {String} token - Bearer token value
* @returns {Test} Test instance for chaining
*/
bearer(token) {}Bearer Token Usage:
request(app)
.get('/protected')
.bearer('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...')
.expect(200);
// Equivalent to:
request(app)
.get('/protected')
.set('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...')
.expect(200);SuperTest extends SuperAgent Request and Agent classes, inheriting all SuperAgent functionality.
Available SuperAgent Methods:
// Request body methods
.send(data) // Set request body (object, string, Buffer)
.type(type) // Set Content-Type header
.accept(type) // Set Accept header
.query(params) // Set query parameters (object or string)
.field(name, val) // Set form field for multipart/form-data
.attach(field, file, filename) // Attach file for multipart uploads
// Request configuration
.set(header, value) // Set request header
.timeout(ms) // Set request timeout (default: no timeout)
.timeout({deadline: ms, response: ms}) // Set deadline and response timeouts
.redirects(count) // Set max redirects (default: 5)
.auth(user, pass, options) // Set basic auth or bearer token
.ca(cert) // Set CA certificate for HTTPS
.key(key) // Set client key for HTTPS
.cert(cert) // Set client certificate for HTTPS
.agent(agent) // Set custom http.Agent
.retry(count, callback) // Retry failed requests
// Response handling
.buffer(boolean) // Enable/disable response buffering
.parse(fn) // Custom response parser function
.serialize(fn) // Custom request serializer function
.responseType(type) // Set expected response type
.maxResponseSize(size) // Set maximum response sizeSuperAgent Integration Example:
// File upload with timeout and custom headers
request(app)
.post('/upload')
.field('name', 'test file')
.field('description', 'Test file upload')
.attach('file', '/path/to/file.txt', 'custom-filename.txt')
.set('X-API-Key', 'secret')
.set('X-Client-Version', '1.0.0')
.timeout({ deadline: 10000, response: 5000 })
.retry(2)
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res) {
if (err) throw err;
console.log('Upload successful:', res.body);
});
// JSON request with query parameters
request(app)
.put('/users/123')
.send({ name: 'John Doe', email: 'john@example.com' })
.query({ includeProfile: true, format: 'json' })
.type('json')
.accept('json')
.expect(200)
.expect('Content-Type', /json/);SuperTest supports various server types and automatically handles server binding.
// Supported app parameter types:
// Function - Express app or middleware function (automatically wrapped in HTTP server)
// Server - Existing HTTP/HTTPS server instance
// String - URL for testing external serversServer Type Examples:
const express = require('express');
const http = require('http');
// Express application (function)
const app = express();
request(app).get('/').expect(200);
// HTTP server instance
const server = http.createServer(app);
request(server).get('/').expect(200);
// External server URL
request('http://localhost:3000').get('/').expect(200);
// HTTPS server with HTTP/2
request(app, { http2: true }).get('/').expect(200);SuperTest provides detailed error reporting for various failure conditions.
Network Errors:
ECONNREFUSED: Connection refusedECONNRESET: Connection reset by peerEPIPE: Broken pipeETIMEDOUT: Operation timed outAssertion Errors:
Error Handling Example:
request(app)
.get('/user')
.expect(200)
.expect({ name: 'john' })
.end(function(err, res) {
if (err) {
// SuperTest error properties:
// err.expected - expected value for assertion
// err.actual - actual value that caused failure
// err.showDiff - whether to show diff (boolean)
// err.status - HTTP status code (if applicable)
// err.code - system error code (ECONNREFUSED, etc.)
console.error('Test failed:', err.message);
// Handle specific error types
if (err.code === 'ECONNREFUSED') {
console.log('Server is not running');
} else if (err.status !== res?.status) {
console.log('HTTP error:', err.status);
}
}
});/**
* Test class extending SuperAgent Request
*/
class Test extends Request {
constructor(app, method, path, optHttp2) {}
expect(a, b, c): Test {}
end(fn): Test {}
bearer(token): Test {}
}
/**
* TestAgent class extending SuperAgent Agent
*/
class TestAgent extends Agent {
constructor(app, options = {}) {}
host(host): TestAgent {}
// HTTP method functions return Test instances
}
/**
* Configuration options
*/
interface Options {
http2?: boolean; // Enable HTTP/2 protocol support
}
/**
* SuperAgent Response object (inherited)
*/
interface Response {
status: number; // HTTP status code
text: string; // Response body as text
body: any; // Parsed response body
header: object; // Response headers
type: string; // Response content type
charset: string; // Response charset
// ... other SuperAgent Response properties
}
/**
* SuperTest Error objects with additional properties
*/
interface SuperTestError extends Error {
expected?: any; // Expected value for failed assertion
actual?: any; // Actual value that caused failure
showDiff?: boolean; // Whether diff should be displayed
status?: number; // HTTP status code (if applicable)
syscall?: string; // System call that failed (for network errors)
code?: string; // Error code (ECONNREFUSED, ETIMEDOUT, etc.)
}
/**
* System error codes for network failures
*/
type NetworkErrorCode =
| 'ECONNREFUSED' // Connection refused
| 'ECONNRESET' // Connection reset by peer
| 'EPIPE' // Broken pipe
| 'ETIMEDOUT'; // Operation timed out