如何在dom中的角元素上使用事件间谍?

时间:2014-02-06 19:08:49

标签: javascript angularjs event-handling jasmine jasmine-jquery

设置

这里我创建,编译,链接和追加元素,然后设置事件间谍。

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

初步测试

这些传递并确认元素存在,在DOM中并且是可见的。

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

事件间谍测试

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

});

我做错了什么?为什么这些事件间谍说点击还没有被触发。

其他信息

我在我正在测试的指令中设置了element.bind('click', ...,我在其中添加了console.log,当我模拟点击事件时会触发它。

1 个答案:

答案 0 :(得分:0)

e.stopImmediatePropagation();

当然,我立即意识到了罪魁祸首。

所以,不出所料,jasmine-jquery不会接受处理程序调用{​​{1}}的事件。

Jasmine-jquery确实提供了一种方法e.stopImmediatePropagation(),但由于我使用的是.toHaveBeenStopped(),看来spy也被扼杀了。