Search code examples
node.jssupertest

Grab specific response properties from SuperTest


I want to be able to grab some response properties and throw them into a variable at times with SuperTest. How can I do this? I don't see the docs doing anything but assertions on the response.

for example I'd like to do something like this:

 var statusCode = request(app).get(uri).header.statusCode;

I'd like to do something like this. Because sometimes I like to split out the asserts into seperate Mocha.js it() tests due to the fact I'm doing BDD and so the 'Thens' in this case are based on the expected response parts so each test is checking for a certain state coming back in a response.

for example I'd like to do this with supertest:

var response = request(app).get(uri);

it('status code returned is 204, function(){
response.status.should.be....you get the idea
};

it('data is a JSON object array', function(){
};

Solution

  • Here is an example how you can accomplish what you want:

    server file app.js:

    var express = require('express');
    var app = express();
    var port = 4040;
    
    var items = [{name: 'iphone'}, {name: 'android'}];
    
    app.get('/api/items', function(req, res) {
      res.status(200).send({items: items});
    });
    
    app.listen(port, function() {
      console.log('server up and running at %s:%s', app.hostname, port);
    });
    
    module.exports = app;
    

    test.js:

    var request = require('supertest');
    var app = require('./app.js');
    var assert = require('assert');
    
    describe('Test API', function() {
      it('should return 200 status code', function(done) {
        request(app)
          .get('/api/items')
          .end(function(err, response) {
            if (err) { return done(err); }
    
            assert.equal(response.status, 200);
            done();
          });
      });
    
      it('should return an array object of items', function(done) {
        request(app)
          .get('/api/items')
          .end(function(err, response) {
            if (err) { return done(err); }
            var items = response.body.items;
    
            assert.equal(Array.isArray(items), true);
            done();
          });
      });  
    
      it('should return a JSON string of items', function(done) {
        request(app)
          .get('/api/items')
          .end(function(err, response) {
            if (err) { return done(err); }
    
            try {
              JSON.parse(response.text);
              done();
            } catch(e) {
              done(e);
            }
          });
      });
    
    });
    

    You can see some examples here on the superagent github library since supertest is based on superagent library.