[英]Unit testing Angular directive click handler
我有一条指令,将点击处理程序添加到元素:
module.directive('toggleSection', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('click', function (event) {
scope.$apply(function () {
var scopeProp = 'show' + attrs.toggleSection;
event.preventDefault();
event.stopPropagation();
scope[scopeProp] = !scope[scopeProp];
return false;
});
});
}
};
}]);
单击该元素时,它将在范围上切换另一个属性,该另一个属性与ng-show
绑定。 它正在应用程序中正常工作。
我为指令添加了以下测试:
(function () {
'use strict';
// get the app module from Angular
beforeEach(module('app'));
describe('myCtrl', function () {
var $scope, $rootScope;
beforeEach(inject(function ($controller, _$rootScope_) {
$scope = {};
$controller('myCtrl', { $scope: $scope });
$rootScope = _$rootScope_;
}));
describe('the toggleSection directive', function () {
var testElement;
beforeEach(function () {
testElement = $compile('<a toggle-section="Test" href="#">Collapse section</a>')($rootScope);
$rootScope.$digest();
});
it('inverts the value of the specified scope property', function () {
$scope.showTest = false;
testElement.click();
expect($scope.showTest).toEqual(true);
});
});
});
在实际的代码中,有一些属性,例如$scope.showSection1 = false
,通过在指令中添加控制台日志,我可以在单击绑定元素之前和之后看到属性,并且它们具有预期的值(例如,该属性以false
开头,并且在您之后一旦切换为true
请点击切换元素。
但是,测试始终会失败,并显示“ Expected false to equal true”。 我认为这与$apply
方法有关,因为当我运行测试时,范围内似乎没有show属性。
我拥有的其他测试(即使在相同的spec文件中)也没有使用该指令,可以看到范围内的属性很好。
我究竟做错了什么?
测试中有几件事需要更改:
1-范围创建应从$scope = {}
更改为$scope = $rootScope.$new();
2-指令不应编译为rootScope,而应编译为scope
3-该指令应首先通过angularjs.element创建,然后进行编译:
element = angular.element('<my-directive/>');
compile(element)(scope);
scope.$digest();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.