Reputation: 607
I'm having this directive
which is just working fine:
(function () {
'use strict';
angular
.module('app.core')
.directive('selectOnClick', selectOnClick);
// @ngInject
function selectOnClick() {
return {
restrict : 'A',
link : function (scope, element) {
element.on('click', function () {
this.select();
scope.testValue++; // only to test if it is triggered
});
}
};
}
})();
In my test, I want to check if the click event is triggered and if the element is selected. Like you can see below, I trigger a click event in the test and run $scope.$digest()
, but neither the scope variable is incremented nor the click event is triggered.
Any ideas why?
describe('test selectOnClickDirective', function () {
'use strict';
var $scope,
$compile,
element;
beforeEach(module('app.core'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$scope = _$rootScope_.$new();
$compile = _$compile_;
element = $compile('<input select-on-click type="text">')($scope);
$scope.$digest();
}));
it('should trigger an click event', function () {
$scope.testValue = 10;
var input = element.find('input');
input.trigger('click');
$scope.$digest();
expect('click').toHaveBeenTriggeredOn(input);
expect($scope.testValue).toEqual(11);
});
it('should select the element when clicked on it', function () {
//expect(element.find('input').is(':selected')).toBe(true);
});
});
Upvotes: 0
Views: 6303
Reputation: 151
You can use element
that you've compiled, and use triggerHandler
which passes a dummy event object to the handlers.
From the Angular Docs: triggerHandler()
- Passes a dummy event object to handlers.
So you need to write:
element.triggerHandler('click');
Upvotes: 0
Reputation: 607
The Problem was, that element.find
searches for child elements in this element. So I had to just use element
.
Solution will be this:
it('should trigger an click event', function () {
$scope.testValue = 10;
element.trigger('click');
$scope.$digest();
expect('click').toHaveBeenTriggeredOn(element);
expect($scope.testValue).toEqual(11);
});
Upvotes: 1
Reputation: 5977
Try
input.triggerHandler('click');
instead of your
input.trigger('click');
Upvotes: 1