SuperTest

Super-agent driven library for testing node.js HTTP servers using a fluent ...

README


[![code coverage][coverage-badge]][coverage]
[![Build Status][travis-badge]][travis]
[![Dependencies][dependencies-badge]][dependencies]
[![PRs Welcome][prs-badge]][prs]
[![MIT License][license-badge]][license]

HTTP assertions made easy via superagent. Maintained for Forward Email and Lad.


About


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.

Getting Started


Install SuperTest as an npm module and save it to your package.json file as a development dependency:

  1. ```bash
  2. npm install supertest --save-dev
  3. ```

  Once installed it can now be referenced by simply calling require('supertest');

Example


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:

  1. ```js
  2. const request = require('supertest');
  3. const assert = require('assert');
  4. const express = require('express');

  5. const app = express();

  6. app.get('/user', function(req, res) {
  7.   res.status(200).json({ name: 'john' });
  8. });

  9. request(app)
  10.   .get('/user')
  11.   .expect('Content-Type', /json/)
  12.   .expect('Content-Length', '15')
  13.   .expect(200)
  14.   .end(function(err, res) {
  15.     if (err) throw err;
  16.   });
  17. ```

To enable http2 protocol, simply append an options to request or request.agent:

  1. ```js
  2. const request = require('supertest');
  3. const express = require('express');

  4. const app = express();

  5. app.get('/user', function(req, res) {
  6.   res.status(200).json({ name: 'john' });
  7. });

  8. request(app, { http2: true })
  9.   .get('/user')
  10.   .expect('Content-Type', /json/)
  11.   .expect('Content-Length', '15')
  12.   .expect(200)
  13.   .end(function(err, res) {
  14.     if (err) throw err;
  15.   });

  16. request.agent(app, { http2: true })
  17.   .get('/user')
  18.   .expect('Content-Type', /json/)
  19.   .expect('Content-Length', '15')
  20.   .expect(200)
  21.   .end(function(err, res) {
  22.     if (err) throw err;
  23.   });
  24. ```

Here's an example with mocha, note how you can pass done straight to any of the .expect() calls:

  1. ```js
  2. describe('GET /user', function() {
  3.   it('responds with json', function(done) {
  4.     request(app)
  5.       .get('/user')
  6.       .set('Accept', 'application/json')
  7.       .expect('Content-Type', /json/)
  8.       .expect(200, done);
  9.   });
  10. });
  11. ```

You can use auth method to pass HTTP username and password in the same way as in the superagent:

  1. ```js
  2. describe('GET /user', function() {
  3.   it('responds with json', function(done) {
  4.     request(app)
  5.       .get('/user')
  6.       .auth('username', 'password')
  7.       .set('Accept', 'application/json')
  8.       .expect('Content-Type', /json/)
  9.       .expect(200, done);
  10.   });
  11. });
  12. ```

One thing to note with the above statement is that superagent now sends any HTTP
error (anything other than a 2XX response code) to the callback as the first argument if
you do not add a status code expect (i.e. .expect(302)).

If you are using the .end() method .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:

  1. ```js
  2. describe('POST /users', function() {
  3.   it('responds with json', function(done) {
  4.     request(app)
  5.       .post('/users')
  6.       .send({name: 'john'})
  7.       .set('Accept', 'application/json')
  8.       .expect('Content-Type', /json/)
  9.       .expect(200)
  10.       .end(function(err, res) {
  11.         if (err) return done(err);
  12.         return done();
  13.       });
  14.   });
  15. });
  16. ```

You can also use promises:

  1. ```js
  2. describe('GET /users', function() {
  3.   it('responds with json', function() {
  4.     return request(app)
  5.       .get('/users')
  6.       .set('Accept', 'application/json')
  7.       .expect('Content-Type', /json/)
  8.       .expect(200)
  9.       .then(response => {
  10.           assert(response.body.email, 'foo@bar.com')
  11.       })
  12.   });
  13. });
  14. ```

Or async/await syntax:

  1. ```js
  2. describe('GET /users', function() {
  3.   it('responds with json', async function() {
  4.     const response = await request(app)
  5.       .get('/users')
  6.       .set('Accept', 'application/json')
  7.     expect(response.headers["Content-Type"]).toMatch(/json/);
  8.     expect(response.status).toEqual(200);
  9.     expect(response.body.email).toEqual('foo@bar.com');
  10.   });
  11. });
  12. ```

Expectations are run in the order of definition. This characteristic can be used
to modify the response body or headers before executing an assertion.

  1. ```js
  2. describe('POST /user', function() {
  3.   it('user.name should be an case-insensitive match for "john"', function(done) {
  4.     request(app)
  5.       .post('/user')
  6.       .send('name=john') // x-www-form-urlencoded upload
  7.       .set('Accept', 'application/json')
  8.       .expect(function(res) {
  9.         res.body.id = 'some fixed id';
  10.         res.body.name = res.body.name.toLowerCase();
  11.       })
  12.       .expect(200, {
  13.         id: 'some fixed id',
  14.         name: 'john'
  15.       }, done);
  16.   });
  17. });
  18. ```

Anything you can do with superagent, you can do with supertest - for example multipart file uploads!

  1. ```js
  2. request(app)
  3.   .post('/')
  4.   .field('name', 'my awesome avatar')
  5.   .field('complex_object', '{"attribute": "value"}', {contentType: 'application/json'})
  6.   .attach('avatar', 'test/fixtures/avatar.jpg')
  7.   ...
  8. ```

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, a new Test is created per request.VERB() call.

  1. ```js
  2. request = request('http://localhost:5555');

  3. request.get('/').expect(200, function(err){
  4.   console.log(err);
  5. });

  6. request.get('/').expect('heya', function(err){
  7.   console.log(err);
  8. });
  9. ```

Here's an example with mocha that shows how to persist a request and its cookies:

  1. ```js
  2. const request = require('supertest');
  3. const should = require('should');
  4. const express = require('express');
  5. const cookieParser = require('cookie-parser');

  6. describe('request.agent(app)', function() {
  7.   const app = express();
  8.   app.use(cookieParser());

  9.   app.get('/', function(req, res) {
  10.     res.cookie('cookie', 'hey');
  11.     res.send();
  12.   });

  13.   app.get('/return', function(req, res) {
  14.     if (req.cookies.cookie) res.send(req.cookies.cookie);
  15.     else res.send(':(')
  16.   });

  17.   const agent = request.agent(app);

  18.   it('should save cookies', function(done) {
  19.     agent
  20.     .get('/')
  21.     .expect('set-cookie', 'cookie=hey; Path=/', done);
  22.   });

  23.   it('should send cookies', function(done) {
  24.     agent
  25.     .get('/return')
  26.     .expect('hey', done);
  27.   });
  28. });
  29. ```

There is another example that is introduced by the file agency.js

Here is an example where 2 cookies are set on the request.

  1. ```js
  2. agent(app)
  3.   .get('/api/content')
  4.   .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo'])
  5.   .send()
  6.   .expect(200)
  7.   .end((err, res) => {
  8.     if (err) {
  9.       return done(err);
  10.     }
  11.     expect(res.text).to.be.equal('hey');
  12.     return done();
  13.   });
  14. ```

API


You may use any superagent methods,
including .write(), .pipe() etc and perform assertions in the .end() callback
for lower-level needs.

.expect(status[, fn])


Assert response status code.

.expect(status, body[, fn])


Assert response status code and body.

.expect(body[, fn])


Assert response body text with a string, regular expression, or
parsed body object.

.expect(field, value[, fn])


Assert header field value with a string or regular expression.

.expect(function(res) {})


Pass a custom assertion function. It'll be given the response object to check. If the check fails, throw an error.

  1. ```js
  2. request(app)
  3.   .get('/')
  4.   .expect(hasPreviousAndNextKeys)
  5.   .end(done);

  6. function hasPreviousAndNextKeys(res) {
  7.   if (!('next' in res.body)) throw new Error("missing next key");
  8.   if (!('prev' in res.body)) throw new Error("missing prev key");
  9. }
  10. ```

.end(fn)


Perform the request and invoke fn(err, res).

Notes


Inspired by api-easy minus vows coupling.

License


MIT

[coverage-badge]: https://img.shields.io/codecov/c/github/ladjs/supertest.svg
[coverage]: https://codecov.io/gh/ladjs/supertest
[travis-badge]: https://travis-ci.org/ladjs/supertest.svg?branch=master
[travis]: https://travis-ci.org/ladjs/supertest
[dependencies-badge]: https://david-dm.org/ladjs/supertest/status.svg
[dependencies]: https://david-dm.org/ladjs/supertest
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs]: http://makeapullrequest.com
[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square
[license]: https://github.com/ladjs/supertest/blob/master/LICENSE