使用SinonJs和Mocha测试包含Promise代码块的Restify路由处理程序 [英] Testing Restify Route Handler that contains Promise Code Block, using SinonJs and Mocha
问题描述
我在下面有一个reifyify动作代码块:
I have a restify action code block below:
function retriveAll(req, res, next) {
db.user
.find({where: {id: 1})
.then(function(user){
res.send(user);
})
.catch(function(details){
res.send(details.message);
})
.finally(function(){
next();
});
}
我要测试此操作,以特别验证在此代码块中调用过res.send().然后验证res.send()返回的数据.我正在使用 SinonJs 和 Mocha 作为测试框架.这是上述方法的示例测试代码块.
I want to test this action specifically validating that res.send() was called within this code block. And later on validating the res.send() returned data. I'm using SinonJs and Mocha for testing framework. Here's a sample test code block for the method above.
describe('retrieveAll()', function() {
reqStub = {};
resStub = {send: sinon.stub()};
nextStub = sinon.stub();
beforeEach(function() {
module.retrieveAll(reqStub, resStub, nextStub);
});
// this doesn't work
// and the sub.calledCount is 0
// i wonder if it's because the res.send() is inside a Promise code block???
// if I move the res.send() out from Promise, just before next(), then it works
it('should call res.send()', function() {
sinon.assert.calledOnce(resStub.send);
});
// this one works
it('should call next', function() {
sinon.assert.calledOnce(nextStub);
});
});
有人可以给我一些启示吗?
Could someone shed some light?
推荐答案
beforeEach()
的回调函数接收一个done
参数,可以调用该参数来表示异步完成.由于您的retriveAll
函数将最后一个参数(next
)称为最后一个动作,因此您可以将该参数作为next
值传递,它应该可以工作:
The beforeEach()
's callback function receives a done
parameter that can be called to signal an asynchronous completion. Since your retriveAll
function calls the last parameter (next
) as the last action, you can pass that parameter as the next
value and it should work:
beforeEach(function(done) {
module.retrieveAll(reqStub, resStub, done);
});
但是您将松开nextStub
,所以...或者,您可以在该done
函数上 spy :
You will however loose the nextStub
, so... alternatively, you could spy on that done
function:
describe('retrieveAll()', function() {
var reqStub = {};
var resStub = {send: sinon.stub()};
var nextSpy;
beforeEach(function(done) {
nextSpy = sinon.spy(done);
module.retrieveAll(reqStub, resStub, done);
});
// this doesn't work
// and the sub.calledCount is 0
// i wonder if it's because the res.send() is inside a Promise code block???
// if I move the res.send() out from Promise, just before next(), then it works
it('should call res.send()', function() {
sinon.assert.calledOnce(resStub.send);
});
// this one works
it('should call next', function() {
sinon.assert.calledOnce(nextSpy);
});
});
这篇关于使用SinonJs和Mocha测试包含Promise代码块的Restify路由处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!