在jasmine测试中没有调用AngularJS指令链接函数

时间:2014-06-24 13:12:04

标签: javascript angularjs jasmine

我正在创建一个在其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);
  }));
});

测试失败,因为时间=== 0.此代码在浏览器中运行良好,但在测试中似乎永远不会调用link函数和服务。有什么想法吗?

plunker:http://plnkr.co/edit/69jK8c

1 个答案:

答案 0 :(得分:14)

您缺少$httpBackend.flush(),告诉模拟$httpBackend返回模板。模板从未加载,因此指令链接功能无法链接。

固定弹药: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);
  }));
});