所以我似乎无法在我的测试中调用一个写在角度指令的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();
返回undefined。
答案 0 :(得分:3)
看起来问题必须与指令中的两个缺失大括号有关。最后}]);
的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);
});
});