Loading a AngularJS Directive TemplateURL into a Unit Test

Objective

To unit test a directive which loads an external template for the HTML.

Technologies

Grunt, Karma, Jasmine, PhantomJS, AngularJS.
Note: It could be classed as an E2E test if we want to mock the $httpbackend and simulate events together with the controller (also to load the templates into the $templateCache) but for this one we’ll do a simple unit test to get it working. Also we could extend our app to use app.directives and pass that into the test. But for this test everything is under the app module.

Example:

In this example I am testing a bootstrap navbar directive to have been appended to the DOM and contain links.
Directory structure:

 

 

package.json

 

spec-unit.conf.js

 

/test/spec-unit/directives/directive.js

 

/app/scripts/directives/navbar.js

 

 

/app/index.html

 

Running the test results in terminal should look like this:
 Image

Tips:

In your directive use Angular.element not $ (jQuery)
You can use Chrome Karma debugger to see whats going either use console.log or debugger; in your code as usual.
 Image
Image

refs:

Sam is a passionate web developer, online entrepreneur and investor. In his spare time he enjoys coding, playing chess and reading.

Leave a Reply

Your email address will not be published. Required fields are marked *