最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I trigger a click event in a Jasmine unit test for an Angular Directive? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Aug 10, 2016 at 17:07 AgmLauncherAgmLauncher 7,27010 gold badges49 silver badges71 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You may need to add jasmine-jquery to your project they have specific functions to acplish 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.

发布评论

评论列表(0)

  1. 暂无评论