我有一个身份验证中间件需要测试,该中间件对身份验证服务进行外部调用,并根据返回的状态码调用下一个中间件/控制器或返回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)调用是异步的,在调用返回之前就到达了断言部分。我一直在处理这个问题整整一天了,请帮帮我。