Search code examples
node.jsrestmocha.jssupertest

request rest api and return response values for a mocha test


Inside a meteor appliation, i want to test some rest functions, therefore i need to do some authentication.

In my testcase, i want to return some auth data from a function:

const supertest = require('supertest');

function loginUser(auth) {
  return function(done) {
    request
      .post('/users/login')
      .send({
        username: 'user'
        password: '123',
      })
      .expect(200)
      .end(onResponse);

    function onResponse(err, res) {
      auth.token = res.body.token;
      return done();
    }
  };
}

inside this test:

it('auth test by helper function', function () {
  let auth = {};
  auth = loginUser(auth)(done);
  //access auth settings here like:
  //auth.token
});

onResponse is never called and auth is always {}

I am using supertest for requests 3.0.0 and mocha 4.1.0 as testrunner (The rest api is simple:json-routes)

UPDATE

It seems like the return 'function(done)' is never called...

Ok i fixed the call to auth = loginUser(auth)(done);

Now the call is done but auth is undefined after the call


Solution

  • Your function loginUser(auth) returns another function. So you should call that function as well like this:

    it('auth test by helper function', function (done) { // pass done so mocha knows it needs to wait for the response ...
      let auth = {};
      loginUser(auth)(function() {
         //access auth settings here like:
         //auth.token
         done();
      });       
    });