angularjs - Unit test angular right-click directive -
i want write jasmine unit test angularjs directive. directive binds contextmenu event handler function 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>
unit test:
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 contextmenu event binding element', function () { // compile piece of html containing directive var element = $compile("<div my-right-click='myfunction'></div>")($rootscope)[0]; // check compiled element contains templated content expect(element.attributes["my-right-click"].value).toequal("myfunction"); expect(element.attributes["oncontextmenu"]).tonotequal(undefined); }) });
the unit test fails on last assertion, because element oncontextmenu
attribute undefined. however, directive correctly invokes function in application itself. how can determine in test function has been correctly bound element's oncontextmenu event?
edit
or, alternative , better approach, how can wire event handler , invoke via directive in test can check gets called?
i've had same issue , solution...
use triggerhandler dispatch event, test supplied function 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
Comments
Post a Comment