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

How to handle q and promise for unit test case

本文关键字:promise 测试用例 处理单元      更新时间:2023-09-26

我有一个api,它是使用q和promise创建的。我需要为那个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');
     });        
});

有人能告诉我怎么做吗?

这是不可能进行测试的,因为您没有公开任何方法来知道函数何时完成。你需要打电话的人知道这一点。

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

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