I've tried following the format of the ng-directive-testing repo for a directive I've written. The directive basically renders an overlay when the user clicks on an element. Here's the directive (simplified):
mod.directive('uiCopyLinkDialog', function(){ return { restrict: 'A', link: function(scope, element, attrs) { var $elm = angular.element(element); element.bind('click', function(event) { $elm.addClass('test'); }); } }; });
The test I'm writing looks like this:
describe('pre-compiled link', function () { beforeEach(mocks.inject(function($compile, $rootScope) { scope = $rootScope; element = angular.element('<span class="foo" ui-copy-link-dialog="url"></span>'); $compile(element)(scope); scope.$digest(); })); it("should change the class when clicked", function () { element.click(); // this returns "'undefined' is not a function" element[0].click(); // so does this $(elm).click(); // this uses jquery and doesn't *seem* to fail waits(500); // hack to see if it was a race condition expect(elm.className).toContain('test'); // always fails }); });
You can see in the test that I try several ways to trigger the click()
event on the link, with most of them giving an undefined
error.
Can anyone tell me what I'm doing wrong here? Reading the examples this sounds like it's the correct syntax but my test runner (Karma via Grunt) doesn't want to play ball.
In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the . directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive.
AngularJS also provides the ngMock module, which provides mocking for your tests. This is used to inject and mock AngularJS services within unit tests.
Testing in AngularJS is achieved by using the karma framework, a framework which has been developed by Google itself. The karma framework is installed using the node package manager. The key modules which are required to be installed for basic testing are karma, karma-chrome-launcher ,karma-jasmine, and karma-cli.
You can use triggerHandler, part of JQLite.
I used this to trigger a click event on a directive...
element = angular.element("<div myDirective-on='click'></div>"); compiled = $compile(element)($rootScope); compiled.triggerHandler('click');
Full example available on this blog post: http://sravi-kiran.blogspot.co.nz/2013/12/TriggeringEventsInAngularJsDirectiveTests.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With