AngularJS Testing Tips: Testing Directives

article

#1

Originally published at: http://www.sitepoint.com/angular-testing-tips-testing-directives/
Unit tests are an essential part of software development as they help you in releasing less buggy code. Testing is one of the several things that one has to do to improve code quality. AngularJS is created with testing in mind and any code written on top of the framework can be tested easily.

In my last article on testing, I covered Unit testing Controllers, Services and Providers. This article continues the discussion on testing with directives. Directives are different from other components because they aren’t used as objects in the JavaScript code, but in HTML templates of the application. We write directives to perform DOM manipulations and we can’t ignore them in unit tests as they play an important role. Besides, they directly affect the usability of the application.

I encourage you to check out the past article on Mocking dependencies in AngularJS tests, as we will be using some of the techniques from that article here. In case you want to play with the code developed in this tutorial, you can take a look at the GitHub repository I set up for you.

Testing Directives

Directives are the most important and most complex components in AngularJS. Testing directives is tricky, as they are not called like a function. In applications, the directives are declaratively applied on the HTML template. Their actions are executed when the template is compiled and a user interacts with the directive. When performing unit tests, we need to automate the user actions and manually compile the HTML in order to test the functionality of the directives.
Continue reading this article on SitePoint


#2

Using html2js is an ugly way to test directive smile

First of all, the template markup isn't frozen.

It can, and would probably change when the project grows. You still can mock $templateCache and fill it, breaking dependency.

Consider this directive:

angular.module('sampleDirectives', ['templates-main'])
.directive('fourthDirective', function () {
return {
templateUrl: 'directives/sampleTemplate.html'
};
});

In your test, you just need to do this:

$templateCache.put("directives/sampleTemplate.html", "myFakeContent");

You still can test the updated scope, but right now you're not depending of an evolving file.


#3

Kogratte,

Sure, $templateCache is a good alternative to test the directive without loading the template. But, at times the template would have certain important elements and you need to make sure that these elements are not modified or, removed from the template so that the directive works as expected. To assert such cases, you need to have tests verifying them against the actual template rather than a mocked response.


closed #4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.