NodeJS:如何测试调用外部API的中间件

3

我有一个身份验证中间件需要测试,该中间件对身份验证服务进行外部调用,并根据返回的状态码调用下一个中间件/控制器或返回401状态码。就像我下面的示例一样。

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)
      }
  })
}

我使用SinonJS、nock和node-mocks-http进行测试,我的简单测试如下:
 // 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();
});

测试总是失败并返回 false,我觉得原因是因为针(needle)调用是异步的,在调用返回之前就到达了断言部分。我一直在处理这个问题整整一天了,请帮帮我。

1个回答

2
你需要将测试设置与断言分开。
// 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
});

1
感谢@Derick Bailey,非常感激。我发现在SO上提问比读大多数书籍更有收获,我学到了更多。它的效果正是我想要的。 - George
我在测试中遇到了问题,当返回的状态码不是200时,该如何处理? - George

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接