Reuse Supertest tests on a remote URL

Shane Stillwell picture Shane Stillwell · Dec 6, 2012 · Viewed 8.6k times · Source

I'm using MochaJS and SuperTest to test my API during development and absolutely LOVE it.

However, I would like to also turn these same tests to remotely tests my staging server before pushing the code out to production.

Is there a way to supply request with a remote URL or proxy to a remote URL?

Here is a sample of a test I use

        request(app)
        .get('/api/photo/' + photo._id)
        .set(apiKeyName, apiKey)
        .end(function(err, res) {
            if (err) throw err;
            if (res.body._id !== photo._id) throw Error('No _id found');
            done();
        });

Answer

zemirco picture zemirco · Dec 7, 2012

I'm not sure if you can do it with supertest. You can definitely do it with superagent. Supertest is built on superagent. An example would be:

var request = require('superagent');
var should = require('should');

var agent = request.agent();
var host = 'http://www.yourdomain.com'

describe('GET /', function() {
  it('should render the index page', function(done) {
    agent
      .get(host + '/')
      .end(function(err, res) {
        should.not.exist(err);
        res.should.have.status(200);
        done();
      })
  })
})

So you cannot directly use your existing tests. But they are very similiar. And if you add

var app = require('../app.js');

to the top of your tests you easily switch between testing your local app and the deployment on a remote server by changing the host variable

var host = 'http://localhost:3000';

Edit:

Just found an example for supertest in the docs#example

request = request.bind(request, 'http://localhost:5555');  // add your url here

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

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