supertest is a module by that takes testing HTTP easier via superagent. The motivation with this module is to provide a high-level abstraction for testing HTTP, while still allowing you to drop down to the lower-level API provided by superagent.
1
|
npm install supertest |
You may pass an http.Server
, or a Function
to request()
– if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.
Usage
Here’s a basic GET request to an end point.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var request = require( 'supertest' ) , express = require( 'express' ); var app = express(); app.get( '/user' , function (req, res) { res.send(200, { name: 'tobi' }); }); request(app) .get( '/user' ) .expect( 'Content-Type' , /json/) .expect( 'Content-Length' , '20' ) .expect(200) .end( function (err, res) { if (err) throw err; }); |
You can also get all fancy and upload files:
1
2
3
|
request(app) .post( '/' ) .attach( 'avatar' , 'test/fixtures/homeboy.jpg' ) |
Passing the app or url each time is not necessary, if you’re testing the same host you may simply re-assign the request variable with the initialization app or url:
1
2
3
4
5
6
7
8
9
|
request.get( '/' ).expect(200, function (err) { console.log(err); }); request.get( '/' ).expect( 'heya' , function (err) { console.log(err); }); |
Anything you can do with superagent, you can do with supertest. For some strange reason I love testing HTTP end points, this is my goto library for this. Thanks TJ!