【问题标题】:AngularJS directive link function not called in jasmine test茉莉花测试中未调用AngularJS指令链接函数
【发布时间】:2014-06-24 13:12:03
【问题描述】:

我正在创建一个元素指令,该指令在其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 函数和服务似乎从未被调用。有什么想法吗?

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

【问题讨论】:

    标签: javascript angularjs jasmine


    【解决方案1】:

    您缺少$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);
      }));
    });
    

    【讨论】:

    • 我花了很长时间才找到这条信息。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2023-03-27
    • 2013-05-06
    • 1970-01-01
    相关资源
    最近更新 更多