3

In my directive's link function:

$document.on('click.sortColumnList', function () {
    viewToggleController.closeSortColumnList();
    scope.$apply();
});

In my Jasmine unit test:

describe('document click', function () {
    beforeEach(function () {
        this.$document.triggerHandler('click.sortColumnList');
    });

    it('should tell the controller to close the sort column list', function () {
        expect(this.ctrlMock.closeSortColumnList).toHaveBeenCalled();
    });

    it('should trigger a digest cycle', function () {
        expect(this.$scope.$apply).toHaveBeenCalled();
    });
});

This is not actually triggering the event listener. The tests are failing with:

 Expected spy closeSortColumnList to have been called.

The spies are set up correctly, the problem is that the event listener is not firing.

What do you have to do to trigger an event on $document in a Jasmine Angular unit test?

1 Answer 1

4

You may need to add jasmine-jquery to your project they have specific functions to accomplish what you need. Using this you can do something like the following:

var spyEvent = spyOnEvent('#some_element', 'click')
$('#some_element').click()
expect('click').toHaveBeenTriggeredOn('#some_element')

I hope this helps.

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

3 Comments

how can you add jasmine-jquery to the project ?
@CMA I am not really sure of what your set up is, but if you are using the Karma test runner, just add the file location to the files section of the karma.conf.js file.
@CMA, I have never used Chutzpah before, but this link seems like it may be what you need. github.com/mmanela/chutzpah/wiki/Chutzpah-File-References. I think you would want to set jasmine-jquery up through the file references.

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.