• Stars
    star
    13,355
  • Rank 2,327 (Top 0.05 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🕷 Super-agent driven library for testing node.js HTTP servers using a fluent API. Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.

SuperTest

code coverage Build Status Dependencies PRs Welcome MIT 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:

npm install supertest --save-dev

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:

const request = require('supertest');
const assert = require('assert');
const express = require('express');

const app = express();

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

request(app)
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '15')
  .expect(200)
  .end(function(err, res) {
    if (err) throw err;
  });

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

const request = require('supertest');
const express = require('express');

const app = express();

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

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

request.agent(app, { http2: true })
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '15')
  .expect(200)
  .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 /user', function() {
  it('responds with json', function(done) {
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

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

describe('GET /user', function() {
  it('responds with json', function(done) {
    request(app)
      .get('/user')
      .auth('username', 'password')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

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:

describe('POST /users', function() {
  it('responds with json', function(done) {
    request(app)
      .post('/users')
      .send({name: 'john'})
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) return done(err);
        return done();
      });
  });
});

You can also use promises:

describe('GET /users', function() {
  it('responds with json', function() {
    return request(app)
      .get('/users')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .then(response => {
          assert(response.body.email, '[email protected]')
      })
  });
});

Or async/await syntax:

describe('GET /users', function() {
  it('responds with json', async function() {
    const response = await request(app)
      .get('/users')
      .set('Accept', 'application/json')
    expect(response.headers["Content-Type"]).toMatch(/json/);
    expect(response.status).toEqual(200);
    expect(response.body.email).toEqual('[email protected]');
  });
});

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

describe('POST /user', function() {
  it('user.name should be an case-insensitive match for "john"', function(done) {
    request(app)
      .post('/user')
      .send('name=john') // x-www-form-urlencoded upload
      .set('Accept', 'application/json')
      .expect(function(res) {
        res.body.id = 'some fixed id';
        res.body.name = res.body.name.toLowerCase();
      })
      .expect(200, {
        id: 'some fixed id',
        name: 'john'
      }, done);
  });
});

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

request(app)
  .post('/')
  .field('name', 'my awesome avatar')
  .field('complex_object', '{"attribute": "value"}', {contentType: 'application/json'})
  .attach('avatar', 'test/fixtures/avatar.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, a new Test is created per request.VERB() call.

request = request('http://localhost:5555');

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

request.get('/').expect('heya', function(err){
  console.log(err);
});

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

const request = require('supertest');
const should = require('should');
const express = require('express');
const cookieParser = require('cookie-parser');

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

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

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

  const agent = request.agent(app);

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

  it('should send cookies', function(done) {
    agent
    .get('/return')
    .expect('hey', done);
  });
});

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

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

agent(app)
  .get('/api/content')
  .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo'])
  .send()
  .expect(200)
  .end((err, res) => {
    if (err) {
      return done(err);
    }
    expect(res.text).to.be.equal('hey');
    return done();
  });

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.

request(app)
  .get('/')
  .expect(hasPreviousAndNextKeys)
  .end(done);

function hasPreviousAndNextKeys(res) {
  if (!('next' in res.body)) throw new Error("missing next key");
  if (!('prev' in res.body)) throw new Error("missing prev key");
}

.end(fn)

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

Notes

Inspired by api-easy minus vows coupling.

License

MIT

More Repositories

1

superagent

Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
JavaScript
16,475
star
2

lad

Node.js framework made by a former @expressjs TC and @koajs team member. Built for @forwardemail, @spamscanner, @breejs, @cabinjs, and @lassjs.
JavaScript
2,250
star
3

react-native-loading-spinner-overlay

💈 React Native loading spinner overlay
JavaScript
1,583
star
4

frisbee

🐕 Modern fetch-based alternative to axios/superagent/request. Great for React Native.
JavaScript
1,123
star
5

express-cdn

☁️ Node module for delivering optimized, minified, mangled, gzipped assets with Express and Amazon's CDN (S3/CloudFront)
JavaScript
662
star
6

react-native-phone-verification

The best React Native example for phone verification (an alternative to Twitter Digits).
JavaScript
374
star
7

frappe

🆓 Remotely shake your Android devices (including emulators) using a menubar applet and the hotkey ⌘+SHIFT+R
JavaScript
215
star
8

dotenv-parse-variables

Parse dotenv files for Boolean, Array, and Number variable types, built for Lad
JavaScript
122
star
9

i18n-locales

List of locales for i18n
JavaScript
72
star
10

graceful

Gracefully exit HTTP servers (Express/Koa/Fastify/etc), databases (Mongo/Mongoose), Redis clients, Bree job schedulers, and custom handlers.
JavaScript
66
star
11

koa-better-error-handler

A better error-handler for Lad and Koa. Makes `ctx.throw` awesome (best used with koa-404-handler)
JavaScript
52
star
12

chalkline

💄 Draw a big chalkline in your terminal! Great for debugging and reading your log output locally!
JavaScript
35
star
13

cache-pug-templates

Cache Pug templates for Lad/Koa/Express/Connect with Redis
JavaScript
26
star
14

mongoose-slug-plugin

Slugs for Mongoose with history and i18n support (uses speakingurl by default, but you can use any slug library such as limax, slugify, mollusc, or slugme)
JavaScript
22
star
15

express-cachebuster

Provides cross-browser version-control/cache-busting as a dynamic view helper in express.
JavaScript
22
star
16

gulp-jade-usemin

Gulp plugin for running usemin on Jade files
JavaScript
21
star
17

max-listeners-exceeded-warning

Debug and detect "MaxListenersExceededWarning: Possible EventEmitter memory leak detected warnings"
JavaScript
19
star
18

country-language

Query any country's spoken languages or countries where a language is spoken.
JavaScript
12
star
19

mandarin

Automatic i18n phrase translation using Google Translate
JavaScript
12
star
20

i18n

i18n wrapper and Koa middleware for Lad
JavaScript
10
star
21

naivebayes

A ladjs naivebayes package forked from `https://github.com/surmon-china/naivebayes`
JavaScript
10
star
22

web

Web server for Lad
JavaScript
9
star
23

koa-better-flash

Flash message middleware for Koa and Passport
JavaScript
9
star
24

env

Environment configuration loader for Lad
JavaScript
8
star
25

mongoose-common-plugin

Common plugin for Mongoose with standard schema fields and localization support
JavaScript
8
star
26

check-chai

✅ Adds chai helper function `chai.check` for asynchronous testing with multiple expect or assert statements
JavaScript
8
star
27

koa-404-handler

404 handler for Lad and Koa (best used with koa-better-error-handler)
JavaScript
7
star
28

mongoose-validation-error-transform

Automatically transform Mongoose validation error message(s) to a humanized and readable format
JavaScript
7
star
29

express-cdn-cloudfront

Add-on module for express-cdn to provide Amazon CloudFront integration with Amazon S3.
7
star
30

passport

Passport for Lad
JavaScript
6
star
31

lad.sh

Demo for Lad - The Best Node.js Framework
JavaScript
6
star
32

remark-preset-github

GitHub markdown and prose style
JavaScript
6
star
33

dayjs-with-plugins

Day.js with all plugins and locales added out of the box, no need to use dayjs.extend!
JavaScript
6
star
34

is-string-and-not-blank

3x as fast as is-whitespace and whitespace-regex thanks to is-string-blank. This package is a simple function that accepts an argument and returns true if it is a string AND it is not blank.
JavaScript
5
star
35

redis

Redis for Lad
JavaScript
5
star
36

koa-meta

SEO <title> and <meta name="description"> middleware for Koa and Lad
JavaScript
5
star
37

koa-cache-responses

Caching middleware for Koa using koa-cash and route pattern-based matching with path-to-regexp. Made for Lad.
JavaScript
5
star
38

express-cdn-cloudfiles

Add-on module for express-cdn to provide Rackspace CloudFiles integration with built-in Akamai CDN delivery.
5
star
39

lookerupper

✨ :octocat: Copy to your clipboard a package's name and use `CmdOrCtrl+Shift+L` to lookup its documentation on GitHub
JavaScript
5
star
40

express-redirect-loop

Prevent redirect loops with sessions since HTTP referrer header is unreliable
JavaScript
4
star
41

get-paths

Helper function to get an absolute path for a template engine view
JavaScript
4
star
42

spdy-or-http2

Node.js ponyfill for HTTP/2 support (uses native http2 module or falls back to spdy)
JavaScript
4
star
43

proxy

Proxy for Lad
JavaScript
4
star
44

api

API server for Lad
JavaScript
4
star
45

koa-views-render

Simple render(page, locals) middleware for Koa and Lad (uses koa-views)
JavaScript
4
star
46

koa-better-timeout

Response timeout middleware for Koa and Lad (uses Boom by default)
JavaScript
4
star
47

express-jade

Express middleware to compile client-side Jade templates as template functions in the `window.jade` namespace.
JavaScript
4
star
48

koa-redis-ratelimit

*DOES NOT WORK DUE TO `ratelimiter`, PLEASE USE https://github.com/scttcper/koa-simple-ratelimit INSTEAD* Rate limiting middleware backed by Redis for Koa v2+, built for 🐊 CrocodileJS
JavaScript
3
star
49

mongoose

Mongoose helper for Lad
JavaScript
3
star
50

koa-redirect-loop

Prevent redirect loops with sessions since HTTP referrer header is unreliable and ensures sessions are saved upon redirect
JavaScript
3
star
51

store-ip-address

Stores a user's IP address in the background for Lad
JavaScript
3
star
52

message-headers

Automatically updated list of RFC HTTP permanent and provisional headers from IANA (https://www.iana.org/assignments/message-headers/message-headers.xhtml)
JavaScript
3
star
53

mongoose-omit-common-fields

Array of common fields to emit for Mongoose toObject/toJSON (helpful for security)
JavaScript
3
star
54

mongoose-model-agenda

Mongoose model for Agenda
JavaScript
3
star
55

express-cdn-cloudflare

Add-on module for express-cdn to provide CloudFlare CDN integration with Amazon S3.
3
star
56

koa-better-static

Static file serving middleware for Koa. Forked from an inactive project and maintained for Lad.
JavaScript
3
star
57

koa-manifest-rev

Dynamically load assets into your views from your `rev-manifest.json` manifest revision file.
JavaScript
3
star
58

stop-agenda

Gracefully stop Agenda and cancel recurring jobs
JavaScript
2
star
59

assets

Assets for Lad
JavaScript
2
star
60

policies

Policies helper for Lad
JavaScript
2
star
61

shared-config

Shared configuration for Lad's API and Web servers
JavaScript
2
star
62

manifest-rev

Dynamically load assets into your views, emails, etc. from your `rev-manifest.json` manifest revision file.
JavaScript
2
star
63

gulp-envify

Gulp plugin for envify without browserify (maintained fork of https://github.com/tomashanacek/gulp-envify)
JavaScript
2
star
64

preserve-qs

Preserve querystrings during redirect and creating new URLs for Node.js and browser environments (supports Lad, Koa, Express, and Connect)
JavaScript
2
star
65

juice-resources-promise

Simple helper function to convert juice.juiceResources into a Promise
JavaScript
2
star
66

gulp-haschanged-deps-async

Deep dependency recursive modified time comparison to ensure your files only re-compile when needed
JavaScript
2
star
67

pick-original

Transform an Object that was transformed to return only the original properties recursively picked if they are not undefined.
JavaScript
1
star
68

koa-cors-gate

JavaScript
1
star
69

store-sessions

Store/manage user sessions in the background for Lad
JavaScript
1
star
70

mongoose-error-messages

Better error messages for Mongoose, built for Lad
JavaScript
1
star
71

lad-template

sao template for lad
JavaScript
1
star
72

state-helper

State helper for Lad
JavaScript
1
star
73

agenda

Agenda for Lad
JavaScript
1
star
74

bull

Bull for Lad
JavaScript
1
star
75

browserslist-config

Browserslist config for Lad
JavaScript
1
star