本文介绍了在角控制器的$ q.all输出测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器执行类似下面(请注意,我没有表现出为了简单起见所有依赖):

My controller does something like below (pls note i had not shown all dependencies for sake of simplicity):

.controller('demo',function(){

      fn1(){
          var defereed = $q.defer;
          /* fetch data from server and once the data is fetched perform a resolve */
          return deferred.promise;
      }

     fn2(){
        var defereed = $q.defer;
          /* fetch data from server and once the data is fetched perform a resolve*/      
          return deferred.promise;
     }

     fun3() { /*makes some server side calls and updates the view*/}

     $q.all([fn1(),fn2()] .then(function(result){
           if (result[0]) { fn3();}
       });

    }

在这种情况下,我已经有一个很难检测是否fn3的()被调用。我也没能得到FN1()和FN2()来解决,这样我可以测试fn3的()

Under such circumstances I have having a hard time testing whether fn3() was called. I am also not able to get fn1() and fn2() to resolve so that i can test fn3()

任何提示将AP preciated。

Any tips will be appreciated.

推荐答案

最后figuered的解决方案。对于那些有兴趣检查该plnkr:

Finally figuered a solution .. For those interested check this plnkr:http://plnkr.co/HkaQdH

describe('Testing: MainCtrl', function() {
  var $scope = null;
  var ctrl = null;
  var mockInitService;
  var defer1,defer2;
  var $q;

  beforeEach(module('plunker'));

  beforeEach(inject(function($rootScope, $controller,$q) {
    $scope = $rootScope.$new();
    $q = $q;

    mockInitService = {
      fn1: function(){},
      fn2: function(){},
      fn3: function(){}
    };
    defer1 = $q.defer();
    defer2 = $q.defer();

    spyOn(mockInitService,'fn1').and.returnValue(defer1.promise);
    spyOn(mockInitService,'fn2').and.returnValue(defer2.promise);
    spyOn(mockInitService,'fn3');

    createController = function() {
      return $controller('MainCtrl', {
        $scope: $scope,
        InitService: mockInitService
      });
    }

  }));

  it('Should call InitService.fn3', function() {
    ctrl = createController();
    defer1.resolve();
    defer2.resolve();
    $scope.$digest();
    expect(mockInitService.fn3).toHaveBeenCalled();
  });

});

这篇关于在角控制器的$ q.all输出测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 18:14