0

I've simple directive with an event handler.

angular.module('app')
    .directive('acc', function () {
      return {
        restrict: 'A',
        link: function (scope, element) {
            scope.a = 0;
            scope.func = function() {
                console.log('h2.clicked !!');
                scope.a = 1;
            };

          element.on('click', 'h2', scope.func);
        }
      };
    });

And simple test

describe('Directive: acc', function () {
    beforeEach(module('app'));

    var element,
        scope;

    var clickContext = 'h2';
    var onSpy;

    beforeEach(inject(function ($compile, $rootScope) {
        scope = $rootScope.$new();

        onSpy = spyOn($.fn, 'on').and.callThrough();

        element = angular.element('<nav acc><h2></h2></nav>');
        element = $compile(element)(scope);
        scope.$digest();
    }));

    it('should set click handler', function () {
        expect(onSpy).toHaveBeenCalledWith('click', clickContext, jasmine.any(Function));
    });

    describe('click handler behaviour', function () {

        beforeEach(function () {
            element.find('h2').triggerHandler('click');
        });


        it('handler should be called', function () {
          expect(scope.a).toBe(1);
        });
    });
});

I want to invoke handler before each test case for verify behaviour. How to do it? I use jasmine for unit testing.

1 Answer 1

1

Have you tried calling scope.$digest(); after the .click()?

Sign up to request clarification or add additional context in comments.

1 Comment

I tried element.find('h2').triggerHandler('click');scope.$digest(); this doesn't work, but when I changed triggerHandler to trigger all will work. Thank you

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.