如何在Jasmine单元测试中触发Angular Directive的click事件?

时间:2016-08-10 17:07:39

标签: javascript angularjs unit-testing jasmine

在我的指令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上触发事件?

1 个答案:

答案 0 :(得分:3)

您可能需要将jasmine-jquery添加到他们拥有specific functions的项目中,以实现您的需求。使用此功能,您可以执行以下操作:

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

我希望这会有所帮助。

相关问题