1

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?

João Dias
  • 238
  • 2
  • 16

2 Answers2

0

You shall call digest to notify to angular that something has changed:

element.on('load', function(event) {
    scope.callback({ event: event });
    scope.$digest();
});
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • Like I said, the directive works fine, and it's been running for months in the real world. The problem is the test. ): – João Dias Jul 02 '15 at 09:18
0

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

João Dias
  • 238
  • 2
  • 16