7

I would like to start doing unit testing for my angularjs project. That's far from being straight forward, I find it really difficult. I'm using Karma and Jasmine. For testing my routes and the app dependencies, I'm fine. But how would you test a directive like this one ?

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 would I test for instance that the template was found ?

1

1 Answer 1

15

Here is the way to go https://github.com/vojtajina/ng-directive-testing

Basically, you use beforeEach to create, compile and expose an element and it's scope, then you simulate scope changes and event handlers and see if the code reacts and update elements and scope appropriately. Here is a pretty simple example.

Assume this:

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

We expect that when user clicks the element with the directive, myPerson property becomes clicked. This is the behavior we need to test. So we expose the compiled directive (bound to an element) to all specs:

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 just assert 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 here. You need jQuery to this test, to simulate click().

Sign up to request clarification or add additional context in comments.

1 Comment

as for template html, for dynamically loading into $templateCache. you could just use html2js karma pre-processor this boils down to adding templates '.html' to your files in the conf.js file as well preprocessors = { '.html': 'html2js' }; and specify the htmls as modules in your js testing file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.