如何处理单元测试用例的q和承诺

时间:2014-11-12 07:08:58

标签: javascript node.js unit-testing promise sinon

我有一个使用q和promise创建的api。我需要为该api编写单元测试用例。但由于q和承诺,它没有发送回应。 这是我的api

  exports.test=funtion(req,res)
 {

     savedata(req.body).saveQ().then(function(result)
    {
              res.send(result);
    });
 }

这是我对上述api的测试用例

 var req={'body':{name:'xxxxx'}};

 var res={};

 describe('savedata',function()
{
      it('should save data',function(){
         spy=res.send=sinon.spy();
        test(req,res);
        expect(spy.calledOnce).to.be('true');
     });        

});

任何人都可以告诉我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

无法进行测试,因为您无法以任何方式知道该功能何时完成。您需要调用者了解它。

我假设这是摩卡单元测试:

exports.test=funtion(req,res){
    return savedata(req.body).saveQ().then(function(result){ // note the `return`
         res.send(result);
    });
};

可以让你这样做:

it('should save data',function(){
   spy=res.send=sinon.spy();
    return test(req,res).then(function(){  // note the return and the then
        expect(spy.calledOnce).to.be('true');
    });
 });