【问题标题】:How to test a method which returns a promise in sinon?如何测试在 sinon 中返回承诺的方法?
【发布时间】:2014-12-25 23:43:34
【问题描述】:

我有以下控制器:

app.controller('SearchVideosController',

function SearchVideosController($scope, videoRepository) {

  $scope.DoSearch(id, text) {

    // Do some work...

    videoRepository.getVideosForUserBasedOnSearchText(id,text)
                       .then(function(data){
                          // Do something with the data.
                       });

   };

};

我的 videoRepository.getVideosForUserBasedOnSearchText() 方法使用 $q,我想创建存根来确保调用成功。

我试过了:

 it("should have 3 searched videos", function(){
  ...
    mockVideoRepository.getVideosForUserBasedOnSearchText.returns([]);

但是 get .then() 是未定义的。

不确定如何处理 then() 调用。

【问题讨论】:

    标签: angularjs angularjs-service sinon


    【解决方案1】:

    您需要获取$q 服务实例并使用$q.when 创建一个承诺包装值:-

    mockVideoRepository.getVideosForUserBasedOnSearchText.returns($q.when([]));
    

    还请记住,您需要在预期之前在测试中手动执行摘要循环,以评估 getVideosForUserBasedOnSearchText 调用的结果。只有当一个摘要循环被调用时,promise 才会在你的测试中得到解决。你可以通过获取作用域来做到这一点,并执行$digest$apply。示例:-rootScope.$apply()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-27
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      相关资源
      最近更新 更多