HTTP assertions made easy via super-agent.
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 super-agent.
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.
SuperTest works with any test framework, here is an example without using any test framework at all:
var request = require('supertest')
, express = require('express');
var app = express();
app.get('/user', function(req, res){
res.send(201, { name: 'tobi' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '20')
.expect(201)
.end(function(err, res){
if (err) throw err;
});
Here's an example with mocha, note how you can pass done
straight to any of the .expect()
calls:
describe('GET /users', function(){
it('respond with json', function(done){
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
})
})
If you are using the .end()
syntax with mocha, .expect()
assertions that fail will
not throw - they will return the assertion as an error to the .end()
callback. In
order to fail the test case, you will need to rethrow or pass err
to done()
, as follows:
describe('GET /users', function(){
it('respond with json', function(done){
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect(200)
.end(function(err, res){
if (err)
return done(err) // if response is 500 or 404, test case will fail
done()
});
})
})
Anything you can do with superagent, you can do with supertest - for example multipart file uploads!
request(app)
.post('/')
.attach('test/fixtures/homeboy.jpg', 'avatar')
...
You may use any super-agent methods,
including .write()
, .pipe()
etc and perform assertions in the .end()
callback
for lower-level needs.
Assert response status
code.
Assert response status
code and body
.
Assert response body
text with a string, regular expression, or
parsed body object.
Assert header field
value
with a string or regular expression.
Perform the request and invoke fn(err, res)
.
Inspired by api-easy minus vows coupling.
MIT