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.00
# SuperTest
1
2
SuperTest 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.
3
4
## Package Information
5
6
- **Package Name**: supertest
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install supertest --save-dev`
10
11
## Core Imports
12
13
```javascript
14
const request = require('supertest');
15
```
16
17
For ES modules:
18
19
```javascript
20
import request from 'supertest';
21
```
22
23
You can also import specific classes and functions:
24
25
```javascript
26
const { Test, agent } = require('supertest');
27
```
28
29
## Basic Usage
30
31
```javascript
32
const request = require('supertest');
33
const express = require('express');
34
35
const app = express();
36
37
app.get('/user', function(req, res) {
38
res.status(200).json({ name: 'john' });
39
});
40
41
// Test the app
42
request(app)
43
.get('/user')
44
.expect('Content-Type', /json/)
45
.expect('Content-Length', '15')
46
.expect(200)
47
.end(function(err, res) {
48
if (err) throw err;
49
});
50
```
51
52
## Architecture
53
54
SuperTest is built around several key components:
55
56
- **Main Function**: Creates test request objects with HTTP method functions
57
- **Test Class**: Extends SuperAgent Request with assertion capabilities and server management
58
- **TestAgent Class**: Provides persistent session management with cookie support
59
- **Assertion System**: Fluent API for validating responses (status, headers, body)
60
- **Server Integration**: Automatic binding of function-based apps to ephemeral ports
61
- **HTTP/2 Support**: Optional HTTP/2 protocol support via configuration
62
63
## Capabilities
64
65
### Request Creation
66
67
The main entry point creates test request objects for different HTTP methods.
68
69
```javascript { .api }
70
/**
71
* Test against the given app, returning an object with HTTP method functions
72
* @param {Function|Server|String} app - Express app, HTTP server, or URL string
73
* @param {Object} options - Configuration options including http2 support
74
* @returns {Object} Object with HTTP method functions (get, post, put, delete, etc.)
75
*/
76
function request(app, options = {}) {}
77
```
78
79
**HTTP Method Functions** (dynamically created):
80
81
```javascript { .api }
82
// Standard HTTP methods available on request object
83
get(url) // Returns Test instance for GET request
84
post(url) // Returns Test instance for POST request
85
put(url) // Returns Test instance for PUT request
86
delete(url) // Returns Test instance for DELETE request
87
patch(url) // Returns Test instance for PATCH request
88
head(url) // Returns Test instance for HEAD request
89
options(url) // Returns Test instance for OPTIONS request
90
// ... all other standard HTTP methods
91
92
del(url) // Alias for delete() method for backward compatibility
93
```
94
95
**HTTP/2 Support:**
96
97
```javascript
98
// Enable HTTP/2 protocol
99
request(app, { http2: true })
100
.get('/user')
101
.expect(200);
102
```
103
104
### Test Assertions
105
106
Core assertion functionality for validating HTTP responses.
107
108
```javascript { .api }
109
/**
110
* Test class extending SuperAgent Request with assertion capabilities
111
*/
112
class Test {
113
/**
114
* Chain assertions for HTTP responses with multiple overloads
115
* @param {Number|Array|String|RegExp|Function|Object} a - Status code, body, header name, or custom function
116
* @param {String|Number|RegExp|Function} b - Header value or callback
117
* @param {Function} c - Optional callback
118
* @returns {Test} Test instance for chaining
119
*/
120
expect(a, b, c) {}
121
122
/**
123
* Execute the request and run assertions
124
* @param {Function} fn - Optional callback (err, res) => {}
125
* @returns {Test} Test instance
126
*/
127
end(fn) {}
128
129
/**
130
* Set Authorization Bearer token header
131
* @param {String} token - Bearer token value
132
* @returns {Test} Test instance for chaining
133
*/
134
bearer(token) {}
135
}
136
```
137
138
**Assertion Examples:**
139
140
```javascript
141
// Status code assertions
142
.expect(200)
143
.expect(404)
144
.expect([200, 404]) // Multiple acceptable status codes
145
146
// Body assertions
147
.expect('Some text')
148
.expect({ key: 'value' })
149
.expect(/regex pattern/)
150
151
// Header assertions
152
.expect('Content-Type', 'application/json')
153
.expect('Content-Type', /json/)
154
155
// Custom assertion functions
156
.expect(function(res) {
157
if (res.body.items.length !== 3) {
158
throw new Error('Expected 3 items');
159
}
160
})
161
162
// Combining assertions with callbacks
163
.expect(200, function(err, res) {
164
if (err) throw err;
165
})
166
```
167
168
### Persistent Sessions
169
170
Agent functionality for maintaining sessions across multiple requests.
171
172
```javascript { .api }
173
/**
174
* TestAgent class for persistent HTTP sessions with cookie management
175
* @param {Function|Server} app - Express app or HTTP server
176
* @param {Object} options - Configuration options including http2 support
177
* @returns {TestAgent} Agent instance
178
*/
179
function agent(app, options = {}) {}
180
181
class TestAgent {
182
/**
183
* Set host header for all requests
184
* @param {String} host - Host header value
185
* @returns {TestAgent} Agent instance for chaining
186
*/
187
host(host) {}
188
189
// All HTTP method functions available (same as main request function)
190
get(url, fn) {} // Returns Test instance with agent context
191
post(url, fn) {} // Returns Test instance with agent context
192
// ... all other HTTP methods
193
del(url, fn) {} // Alias for delete method
194
}
195
```
196
197
**Session Usage:**
198
199
```javascript
200
const request = require('supertest');
201
const app = require('./app');
202
203
// Create persistent agent
204
const agent = request.agent(app);
205
206
// Login and get session cookie
207
agent
208
.post('/login')
209
.send({ username: 'user', password: 'pass' })
210
.expect(200)
211
.end(function(err, res) {
212
if (err) throw err;
213
214
// Use the same agent for authenticated requests
215
agent
216
.get('/profile')
217
.expect(200)
218
.end(function(err, res) {
219
// Session cookie automatically included
220
});
221
});
222
```
223
224
### Bearer Token Authentication
225
226
Convenient method for setting Authorization Bearer tokens.
227
228
```javascript { .api }
229
/**
230
* Set Authorization Bearer token header
231
* @param {String} token - Bearer token value
232
* @returns {Test} Test instance for chaining
233
*/
234
bearer(token) {}
235
```
236
237
**Bearer Token Usage:**
238
239
```javascript
240
request(app)
241
.get('/protected')
242
.bearer('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...')
243
.expect(200);
244
245
// Equivalent to:
246
request(app)
247
.get('/protected')
248
.set('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...')
249
.expect(200);
250
```
251
252
### SuperAgent Integration
253
254
SuperTest extends SuperAgent Request and Agent classes, inheriting all SuperAgent functionality.
255
256
**Available SuperAgent Methods:**
257
258
```javascript
259
// Request body methods
260
.send(data) // Set request body (object, string, Buffer)
261
.type(type) // Set Content-Type header
262
.accept(type) // Set Accept header
263
.query(params) // Set query parameters (object or string)
264
.field(name, val) // Set form field for multipart/form-data
265
.attach(field, file, filename) // Attach file for multipart uploads
266
267
// Request configuration
268
.set(header, value) // Set request header
269
.timeout(ms) // Set request timeout (default: no timeout)
270
.timeout({deadline: ms, response: ms}) // Set deadline and response timeouts
271
.redirects(count) // Set max redirects (default: 5)
272
.auth(user, pass, options) // Set basic auth or bearer token
273
.ca(cert) // Set CA certificate for HTTPS
274
.key(key) // Set client key for HTTPS
275
.cert(cert) // Set client certificate for HTTPS
276
.agent(agent) // Set custom http.Agent
277
.retry(count, callback) // Retry failed requests
278
279
// Response handling
280
.buffer(boolean) // Enable/disable response buffering
281
.parse(fn) // Custom response parser function
282
.serialize(fn) // Custom request serializer function
283
.responseType(type) // Set expected response type
284
.maxResponseSize(size) // Set maximum response size
285
```
286
287
**SuperAgent Integration Example:**
288
289
```javascript
290
// File upload with timeout and custom headers
291
request(app)
292
.post('/upload')
293
.field('name', 'test file')
294
.field('description', 'Test file upload')
295
.attach('file', '/path/to/file.txt', 'custom-filename.txt')
296
.set('X-API-Key', 'secret')
297
.set('X-Client-Version', '1.0.0')
298
.timeout({ deadline: 10000, response: 5000 })
299
.retry(2)
300
.expect(200)
301
.expect('Content-Type', /json/)
302
.end(function(err, res) {
303
if (err) throw err;
304
console.log('Upload successful:', res.body);
305
});
306
307
// JSON request with query parameters
308
request(app)
309
.put('/users/123')
310
.send({ name: 'John Doe', email: 'john@example.com' })
311
.query({ includeProfile: true, format: 'json' })
312
.type('json')
313
.accept('json')
314
.expect(200)
315
.expect('Content-Type', /json/);
316
```
317
318
### Server Types
319
320
SuperTest supports various server types and automatically handles server binding.
321
322
```javascript { .api }
323
// Supported app parameter types:
324
// Function - Express app or middleware function (automatically wrapped in HTTP server)
325
// Server - Existing HTTP/HTTPS server instance
326
// String - URL for testing external servers
327
```
328
329
**Server Type Examples:**
330
331
```javascript
332
const express = require('express');
333
const http = require('http');
334
335
// Express application (function)
336
const app = express();
337
request(app).get('/').expect(200);
338
339
// HTTP server instance
340
const server = http.createServer(app);
341
request(server).get('/').expect(200);
342
343
// External server URL
344
request('http://localhost:3000').get('/').expect(200);
345
346
// HTTPS server with HTTP/2
347
request(app, { http2: true }).get('/').expect(200);
348
```
349
350
### Error Handling
351
352
SuperTest provides detailed error reporting for various failure conditions.
353
354
**Network Errors:**
355
- `ECONNREFUSED`: Connection refused
356
- `ECONNRESET`: Connection reset by peer
357
- `EPIPE`: Broken pipe
358
- `ETIMEDOUT`: Operation timed out
359
360
**Assertion Errors:**
361
- Status code mismatches with expected vs actual values
362
- Body content differences with detailed diffs
363
- Header value mismatches with regex support
364
- Custom assertion function failures with stack traces
365
366
**Error Handling Example:**
367
368
```javascript
369
request(app)
370
.get('/user')
371
.expect(200)
372
.expect({ name: 'john' })
373
.end(function(err, res) {
374
if (err) {
375
// SuperTest error properties:
376
// err.expected - expected value for assertion
377
// err.actual - actual value that caused failure
378
// err.showDiff - whether to show diff (boolean)
379
// err.status - HTTP status code (if applicable)
380
// err.code - system error code (ECONNREFUSED, etc.)
381
console.error('Test failed:', err.message);
382
383
// Handle specific error types
384
if (err.code === 'ECONNREFUSED') {
385
console.log('Server is not running');
386
} else if (err.status !== res?.status) {
387
console.log('HTTP error:', err.status);
388
}
389
}
390
});
391
```
392
393
## Types
394
395
```javascript { .api }
396
/**
397
* Test class extending SuperAgent Request
398
*/
399
class Test extends Request {
400
constructor(app, method, path, optHttp2) {}
401
expect(a, b, c): Test {}
402
end(fn): Test {}
403
bearer(token): Test {}
404
}
405
406
/**
407
* TestAgent class extending SuperAgent Agent
408
*/
409
class TestAgent extends Agent {
410
constructor(app, options = {}) {}
411
host(host): TestAgent {}
412
// HTTP method functions return Test instances
413
}
414
415
/**
416
* Configuration options
417
*/
418
interface Options {
419
http2?: boolean; // Enable HTTP/2 protocol support
420
}
421
422
/**
423
* SuperAgent Response object (inherited)
424
*/
425
interface Response {
426
status: number; // HTTP status code
427
text: string; // Response body as text
428
body: any; // Parsed response body
429
header: object; // Response headers
430
type: string; // Response content type
431
charset: string; // Response charset
432
// ... other SuperAgent Response properties
433
}
434
435
/**
436
* SuperTest Error objects with additional properties
437
*/
438
interface SuperTestError extends Error {
439
expected?: any; // Expected value for failed assertion
440
actual?: any; // Actual value that caused failure
441
showDiff?: boolean; // Whether diff should be displayed
442
status?: number; // HTTP status code (if applicable)
443
syscall?: string; // System call that failed (for network errors)
444
code?: string; // Error code (ECONNREFUSED, ETIMEDOUT, etc.)
445
}
446
447
/**
448
* System error codes for network failures
449
*/
450
type NetworkErrorCode =
451
| 'ECONNREFUSED' // Connection refused
452
| 'ECONNRESET' // Connection reset by peer
453
| 'EPIPE' // Broken pipe
454
| 'ETIMEDOUT'; // Operation timed out
455
```