Unit test angular right-click directive

删除回忆录丶 提交于 2019-12-01 07:08:17
mbfisher

I've just had exactly the same issue and this was my solution...

Use triggerHandler to dispatch an event, then test that the supplied function is called:

var called;
$rootScope.myFunction = function() {
    called = true;
}

var element = $compile('<div my-right-click="myFunction"></div>')($rootScope);
element.triggerHandler('contextmenu');
expect(called).toEqual(true);

M

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

I choose an alternative approach. You can use a directive to bind specific action on right click, using the contextmenu event:

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

Code example on JSFiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!