如何在Angular指令的Jasmine单元测试中触发一个click事件?

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

本文关键字:一个 事件 click Angular 指令 单元测试 Jasmine      更新时间:2023-09-26

在我的指令的link函数:

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

在Jasmine单元测试中:

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();
    });
});

这实际上并没有触发事件侦听器。

测试失败
 Expected spy closeSortColumnList to have been called.

间谍设置正确,问题是事件侦听器没有触发。

在Jasmine Angular单元测试中,你需要做什么来触发$document上的事件?

您可能需要将jasmine-jquery添加到您的项目中,它们具有特定的功能来完成您需要的功能。使用此命令,您可以执行如下操作:

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