0

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);
    });
});
1
  • first add scope.$apply in order to have angular loop checking changes and apply them in your event callback or it won't work Commented Apr 13, 2016 at 13:03

3 Answers 3

1

Try

input.triggerHandler('click');

instead of your

input.trigger('click');
Sign up to request clarification or add additional context in comments.

Comments

1

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);
});

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.