单元测试角度右键单击指令 [英] Unit test angular right-click directive

查看:25
本文介绍了单元测试角度右键单击指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 AngularJS 指令编写 Jasmine 单元测试.该指令只是将上下文菜单事件处理函数绑定到元素:

I want to write a Jasmine unit test for an AngularJS directive. The directive simply binds a contextmenu event handler function to the element:

var myDirectives = angular.module('myApp.directives', []);

myDirectives.directive('myRightClick', ['$parse', function ($parse) {
    return function (scope, element, attrs) {
        var fn = $parse(attrs.myRightClick);
        element.bind('contextmenu', function (event) {
            scope.$apply(function () {
                event.preventDefault();
                fn(scope, { $event: event });
            });
        });
    };
}]);

<div my-right-click="myFunction"></div>

单元测试:

describe('Unit Test Directives', function () {
    var $compile;
    var $rootScope;

    beforeEach(module('myClientApp.directives'));

    beforeEach(inject(function (_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    it('should wire a contextmenu event binding for the element', function () {
        // Compile a piece of HTML containing the directive
        var element = $compile("<div my-right-click='myFunction'></div>")($rootScope)[0];
        // Check that the compiled element contains the templated content
        expect(element.attributes["my-right-click"].value).toEqual("myFunction");
        expect(element.attributes["oncontextmenu"]).toNotEqual(undefined);
    })
});

最后一个断言的单元测试失败,因为元素 oncontextmenu 属性未定义.但是,该指令会正确调用应用程序本身中的函数.如何在测试中确定函数已正确绑定到元素的 oncontextmenu 事件?

The unit test fails on the last assertion, because the element oncontextmenu attribute is undefined. However, the directive correctly invokes the function in the application itself. How can I determine in a test that a function has been correctly bound to the element's oncontextmenu event?

编辑

或者,作为替代和更好的方法,我如何连接事件处理程序并通过测试中的指令调用它,以便我可以检查它是否确实被调用?

Or, as an alternative and better approach, how can I wire up an event handler and invoke it via the directive in the test so that I can check that it actually gets called?

推荐答案

以下 javascript 函数将在传递给它的 JQueryLite 元素上触发 contextmenu 事件:

The following javascript function will fire the contextmenu event on the JQueryLite element passed to it:

//simulate user right-clicking on the element and check handler gets called
function fireContextMenuEvent(element) {
    if (document.createEvent) {
        var ev = document.createEvent('HTMLEvents');
        ev.initEvent('contextmenu', true, false);
        element.dispatchEvent(ev);
    } else { // Internet Explorer
        element.fireEvent('oncontextmenu');
    }
}

这篇关于单元测试角度右键单击指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆