Question

Setup

Here I am creating, compiling, linking and appending the element then setting up the event spy.

describe('Click Confirm', function() {
    var eventSpy, element, scope;

    beforeEach(module('app'));

    beforeEach(inject(function ($location, $rootScope, $compile) {
        var el, linkFn;

        scope = $rootScope.$new();
        el = angular.element('<a id="testClickConfirm" href="" ng-click="deleteFn()" click-confirm="Test confirmation message">Delete</a>');

        // The $compile method returns the directive's link function
        linkFn = $compile(el);

        // The link function returns the resulting DOM object
        element = linkFn(scope);

        $('body').append(element);

        eventSpy = spyOnEvent('#testClickConfirm', 'click');
    });

Initial tests

These pass and confirm that the element exists, is in the DOM and is visible.

    it('should have set up correctly', function() {
        expect(element).toExist();
        expect(element).toBeInDOM();
        expect(element).toBeVisible();

        expect(el).toExist();
        expect(el).toBeInDOM();
        expect(el).toBeVisible();

        expect($('#testClickConfirm')).toExist();
        expect($('#testClickConfirm')).toBeInDOM();
        expect($('#testClickConfirm')).toBeVisible();
    });

Event Spy Tests

    it('should have set up correctly', function() {
        element.click();
        expect(eventSpy).toHaveBeenTriggered(); // <- FAILS
        expect('click').toHaveBeenTriggeredOn('#testClickConfirm'); // <- FAILS
    });

});

What am I doing wrong? Why are those event spies saying click has not been triggered.

Additional Info

I have an element.bind('click', ... set up in the directive I am testing and I added a console.log inside of it that fires when I simulate the click event.

Was it helpful?

Solution

e.stopImmediatePropagation();

And of course I immediately realize the culprit.

So, unsurprisingly, jasmine-jquery will not pick up on events whose handler calls e.stopImmediatePropagation().

Jasmine-jquery does provide a method .toHaveBeenStopped() but since I am using stopImmediatePropagation() it appears that spy is also being stifled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top