AngularJS指令链接函数在Jasmine测试中未被调用

8
我正在创建一个元素指令,它在其 link 函数中调用一个服务:
app.directive('depositList', ['depositService', function (depositService) {
    return {
        templateUrl: 'depositList.html',
        restrict: 'E',
        scope: {
            status: '@status',
            title: '@title'
        },
        link: function (scope) {
            scope.depositsInfo = depositService.getDeposits({
                status: scope.status
            });
        }
    };
}]);

目前该服务很简单:

app.factory('depositService', function(){
  return {
    getDeposits: function(criteria){
      return 'you searched for : ' + criteria.status;
    }
  };
});

我正在尝试编写一个测试,确保使用正确的状态值调用了depositService.getDeposits()
describe('Testing the directive', function() {
  beforeEach(module('plunker'));
  it('should query for pending deposits', inject(function ($rootScope, $compile, $httpBackend, depositService) {

      spyOn(depositService, 'getDeposits').and.callFake(function(criteria){ 
        return 'blah'; 
      });

      $httpBackend.when('GET', 'depositList.html')
          .respond('<div></div>');

      var elementString = '<deposit-list status="pending" title="blah"></deposit-list>';
      var element = angular.element(elementString);
      var scope = $rootScope.$new();
      $compile(element)(scope);
      scope.$digest();

      var times = depositService.getDeposits.calls.all().length;
      expect(times).toBe(1);
  }));
});

测试失败的原因是 times === 0。这段代码在浏览器中运行得很好,但在测试中,link函数和service从未被调用。有什么想法吗? plunker:http://plnkr.co/edit/69jK8c
1个回答

14

你缺少了$httpBackend.flush(),这个告诉mock $httpBackend返回一个模板。由于模板没有加载,指令链接函数没有可链接的内容。

修复后的plunker: http://plnkr.co/edit/ylgRrz?p=preview

代码:

describe('Testing the directive', function() {
  beforeEach(module('plunker'));
  it('should query for pending deposits', inject(function ($rootScope, $compile, $httpBackend, depositService) {

      spyOn(depositService, 'getDeposits').and.callFake(function(criteria){ 
        return 'blah'; 
      });

      $httpBackend.when('GET', 'depositList.html')
          .respond('<div></div>');

      var elementString = '<deposit-list status="pending" title="blah"></deposit-list>';
      var element = angular.element(elementString);
      var scope = $rootScope.$new();
      $compile(element)(scope);
      scope.$digest();

      $httpBackend.flush();

      var times = depositService.getDeposits.calls.all().length;
      expect(times).toBe(1);
  }));
});

我花了太长时间才找到这条信息。谢谢! :) - Tudmotu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接