简体   繁体   中英

NodeJS: How to test middleware making external call

I have an authentication middleware I will like to test, the middleware makes an external call to an authentication service and based on the returned statusCode either calls the next middleware/controller or it returns a 401 status. Something like what I have below.

var auth = function (req, res, next) {
  needle.get('http://route-auth-service.com', options, function (err, reply) {
      if (reply.statusCode === 200) {
         next();
      } else {
        res.statusCode(401)
      }
  })
}

I use SinonJS , nock , and node-mocks-http for testing and my simple test is as below.

 // require all the packages and auth middleware
 it('should login user, function (done) {
   res = httpMocks.createResponse();
   req = httpMocks.createRequest({
     url: '/api',
     cookies: {
       'session': true
     }
   });

   nock('http://route-auth-service.com')
     .get('/')
     .reply(200);

   var next = sinon.spy()
   auth(res, req, next);
   next.called.should.equal(true); // Fails returns false instead
   done();
});

The test always fails and returns false, I feel that the reason is because the needle call is asynchronous, and before the call returns the assertion part is reached. I have been working on this all day, I need help please.

you need to split the test setup away from the assertion

// this may be "beforeEach"
// depends on what testing framework you're using
before(function(done){
  res = httpMocks.createResponse();
  req = httpMocks.createRequest({
    url: '/api',
    cookies: {
      'session': true
    }
  });

  nock('http://route-auth-service.com').get('/').reply(200);

  var next = sinon.spy();

  auth(res, req, function() {
    next();
    done();
  });
});

it('should login user', function () {
   next.called.should.equal(true); // Fails returns false instead
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM