【问题标题】:How to handle q and promise for unit test case如何处理单元测试用例的 q 和 promise
【发布时间】:2014-11-12 07:08:58
【问题描述】:

我有一个使用 q 和 promise 创建的 api。我需要为该 api 编写单元测试用例。但由于 q 和 promises ,它没有发送响应。 这是我的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');
     });        

});

谁能告诉我如何解决?

【问题讨论】:

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


    【解决方案1】:

    无法进行测试,因为您没有公开任何知道函数何时完成的方式。您需要调用者意识到这一点。

    我假设这是 mocha 单元测试:

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

    【讨论】:

      猜你喜欢
      • 2015-01-24
      • 2016-05-26
      • 2014-06-21
      • 1970-01-01
      • 2016-06-08
      • 2018-02-25
      • 2012-01-08
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多