【问题标题】:how to write unit test case for both normal callback and q and promise callback?如何为普通回调和 q 和 promise 回调编写单元测试用例?
【发布时间】:2015-01-24 09:41:39
【问题描述】:

我有一个函数,我在其中编写了代码来处理这样的回调

exports.CallbackExample=function(req,res)
{
   return callfunction().then(function(data)
  {
      saveData(data).save(function(err,responseData)
     {
          res.send(responseData);

     })

  });

}

我想为上面的代码编写单元测试用例。所以我是这样写的

var res={};
var spy=res.send=sinon.spy();
CallbackExample(req,res).then(function()
{

   expect(spy.calledOnce).to.equal('true');

});

但这不起作用。我认为原因是函数有两个不同的回调,例如第一个回调( Q 和 promises ),第二个是正常回调......我认为可能是因为这个原因,这不起作用。因为这个障碍,我无法前进。那么如何在不对该函数进行任何更改的情况下为该函数编写单元测试用例?....这可能吗? ..我希望你们中的任何人都会帮助我。在此先感谢我正在等待您的解决方案..

【问题讨论】:

    标签: unit-testing callback promise mocha.js q


    【解决方案1】:

    IMO,承诺没有正确链接。使用Deferred解决,

    exports.CallbackExample=function(req,res) {
    
       return callfunction().then(function(data){
         var deferred = Q.defer();
         saveData(data).save(function(err,responseData){
              if (err) {
                deferred.reject(err);
              } else {
                res.send(responseData);
                deferred.resolve(true);
              }
         });
         return deferred.promise;
       });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2019-10-08
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2021-08-10
      • 2019-09-25
      相关资源
      最近更新 更多