AngularJs – Test a directive with external templates

Unit test an angular directive with inline template is straightforward. But whe we have a directive that uses templateUrl the test try to get the template html document and fails because it is not available.

app.directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            templateUrl: 'templates/my-directive.html',

To solve this issue we need to preprocess the templates and make available for tests. We do that using the karma-ng-html2js-preprocessor plugin.

1) First install the preprocessor.
npm install karma-ng-html2js-preprocessor –save-dev

2) Configure the preprocessor in karma.conf.js

plugins: [
    // include the plugin
files: [
    // location of templates, we need this to make available them to the preprocessor
preprocessors: {
    // location of templates
    'app/templates/*.html' : ['ng-html2js']
ngHtml2JsPreprocessor: {
    // strip this prefix from the file path (template cache uses urls as object keys, we need this to match the original url used in the directive)
    stripPrefix: 'app/'

3) Include the Template in the test.
Finally, we need to include the template file in the test in the same way that we include modules.

// load the template



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.