Search code examples
angularjsjasmineangular-directivetestem

How can I test a directive for a load event?


So, I made this simple directive

angular
    .module('cherrytech.common', [])
    .directive('ctOnload', function() {
        return {
            restrict: 'A',
            scope: {
                callback: '&ctOnload'
            },
            link: function(scope, element) {
                element.on('load', function(event) {
                    scope.callback({ event: event });
                });
            }
        };
    });

and it works fine, no issues at all. The callback is called with the event object when the element has finished loading. I'm using this for iframes, but should work on any element that supports the load event.

But then I wanted to test it. I'm using testem with default configuration, and I'm trying this simple test code, but can't get it work:

describe('Directive: ctOnload', function() {
    var element, scope;

    beforeEach(module('cherrytech.common'));

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

        element = '<iframe src="about:blank" ct-onload="loadCallback(event)"></iframe>';

        scope.loadCallback = function(event) { console.log(event); };

        element = $compile(element)(scope);
        scope.$digest();
    }));

    it('should call the scope callback', function() {
        spyOn(scope, 'loadCallback');
        element.triggerHandler('load');
        expect(scope.loadCallback).toHaveBeenCalled();
    });
});

Usually I don't have any issue testing directives, but this event callback is driving me nuts. No matter what I do, I can't get the load event to trigger on the test case. If I replace ct-onload with ng-click and trigger the click event then everything works as expected. What the hell is going on here? Is it a testem issue?


Solution

  • I've decided to kill testem and go back to karma with Chrome launcher. Everything works as it should now.