测试 angular 指令范围方法

Testing angular directive scope method

所以我似乎无法在我的测试中调用在 angular 指令的 internalScope 上编写的方法。

这是我的测试

describe('auto complete directive', function () {

var el, $scope, scope;

beforeEach(module('italic'));
beforeEach(module('stateMock'));
beforeEach(module('allTemplates'));

beforeEach(inject(function ($compile, $rootScope, UserService) {
spyOn(UserService, 'getCurrentUser').and.returnValue({});

$scope = $rootScope;

el = angular.element('<auto-complete collection="" input-value="" enter-event="" focus-on="" />');
$compile(el)($scope);

scope = el.isolateScope();
console.log(scope);
$scope.$apply();

}));

it('should', function () {
 scope.matchSelected();
 expect(scope.showPopup).toBe(false);
}); 
});

和我的指令:

italic.directive('autoComplete', ['$timeout', function($timeout) {
return {
restrict: "E",
template: '',
scope: {
  collection: '=',
  inputValue: '=',
  enterEvent: '=',
  focusOn: '='
},
link: function(scope, element) {      
  scope.matchSelected = function (match) {
    scope.inputValue = match;
    scope.showPopup = false;
  };
 }
}; 
}]);

和错误:

undefined is not a function (called on scope.matchSelected in the test)

我相信它的根源在于 scope = el.isolateScope(); returns 未定义。

看来问题一定与指令中缺少两个大括号有关。 Intead }]); 最后应该是 }}}]);。我建议在缩进和使用大括号时多加小心。如果您正确使用缩进,它将最大限度地减少此类问题。如果您正确缩进,指令将如下所示:

italic.directive('autoComplete', ['$timeout', function($timeout) {
  return {
    restrict: "E",
    template: '',
    scope: {
      collection: '=',
      inputValue: '=',
      enterEvent: '=',
      focusOn: '='
    },
    link: function(scope, element) {      
      scope.matchSelected = function (match) {
        scope.inputValue = match;
        scope.showPopup = false;
      };
    }
  };
}]);

最好在实际中而不是之前创建指令,这样您就可以控制在指令上设置的范围属性。

describe('auto complete directive', function () {
  var $rootScope, $compile;

  beforeEach(module('italic'));

  beforeEach(inject(function (_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('should', function () {
    //Arrange
    var element = $compile("<auto-complete collection=\"\" input-value=\"\" enter-event=\"\" focus-on=\"\" />")($rootScope);

    var scope = element.isolateScope();
    var match = "match";

    //Act
    $rootScope.$digest();
    scope.matchSelected(match);

    //Assert
    expect(scope.showPopup).toBe(false);
  }); 
});

Plunkr