NodeJS:如何测试进行外部调用的中间件
NodeJS: How to test middleware making external call
我有一个我想测试的身份验证中间件,中间件对身份验证服务进行外部调用,并根据返回的 statusCode 调用下一个 middleware/controller 或它 returns 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();
});
测试总是失败returns false,我感觉是因为needle调用是异步的,在调用之前returns到达了断言部分。我整天都在研究这个,我需要帮助。
您需要将测试设置与断言分开
// 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
});
我有一个我想测试的身份验证中间件,中间件对身份验证服务进行外部调用,并根据返回的 statusCode 调用下一个 middleware/controller 或它 returns 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();
});
测试总是失败returns false,我感觉是因为needle调用是异步的,在调用之前returns到达了断言部分。我整天都在研究这个,我需要帮助。
您需要将测试设置与断言分开
// 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
});