Unit Directive Angular Testing

I would like to start doing unit testing for my angularjs project. This is far from easy, it’s very difficult for me. I use karma and jasmine. To test my routes and application dependencies, I'm fine. But how would you test a directive like this?

angular.module('person.directives', []). directive("person", function() { return { restrict: "E", templateUrl: "person/views/person.html", replace: true, scope: { myPerson: '=' }, link: function (scope, element, attrs) { } } 

});

How can I check, for example, that a template has been found?

+7
source share
1 answer

Here is the path https://github.com/vojtajina/ng-directive-testing

Basically, you use beforeEach to create, compile, and expose the element and its scope, then simulate the scope changes and event handlers and check if the code is responsive and updates the elements and scope accordingly. Here is a pretty simple example.

Assume the following:

 scope: { myPerson: '=' }, link: function(scope, element, attr) { element.bind('click', function() {console.log('testes'); scope.$apply('myPerson = "clicked"'); }); } 

We expect that when the user clicks an element with a directive, the myPerson property will become clicked . This is the behavior we need to test. Therefore, we provide a compiled directive (associated with the element) to all specifications:

 var elm, $scope; beforeEach(module('myModule')); beforeEach(inject(function($rootScope, $compile) { $scope = $rootScope.$new(); elm = angular.element('<div t my-person="outsideModel"></div>'); $compile(elm)($scope); })); 

Then you simply state that:

 it('should say hallo to the World', function() { expect($scope.outsideModel).toBeUndefined(); // scope starts undefined elm.click(); // but on click expect($scope.outsideModel).toBe('clicked'); // it become clicked }); 

Plnker is here . You need jQuery for this test to simulate click() .

+15
source

All Articles