gpt4 book ai didi

angularjs - 测试 Angular 定向范围方法

转载 作者:行者123 更新时间:2023-11-28 20:06:04 24 4
gpt4 key购买 nike

所以我似乎无法在我的测试中调用在 Angular 指令的内部作用域上编写的方法。

这是我的测试

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 不是函数(在测试中调用 scope.matchSelected)

我相信它的根源在于 scope = el.isolateScope(); 返回 undefined。

最佳答案

看起来问题一定与指令中缺少两个大括号有关。 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

关于angularjs - 测试 Angular 定向范围方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28548990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com