Search code examples
javascriptangularjsunit-testingng-html2js

Unit testing an Angular Directive


I'm trying to unit test all the directives using karma and jasmine. When I try to load a directive, which has a template called header.html, I get the following error: Error: Unexpected request: GET header.html No more request expected

http://plnkr.co/edit/YTUFXCMdK5JFEwMzzXaR?p=preview

Update: I have the following config in karma.conf.js:

files: [
      'test/client/specs/main.js',
      // 'WebContent/modules/common/header/**/*.html',
      {pattern: 'WebContent/libs/**/*.js', included: false},
      {pattern: 'WebContent/modules/**/*.js', included: false},
      {pattern: 'WebContent/modules/common/header/tmpl/*.html', included: false},
      {pattern: 'test/client/specs/**/*spec.js', included: false}
    ],


    // generate js files from html templates
    preprocessors: {
      'WebContent/modules/common/header/**/*.html': ['ng-html2js']
    },


    ngHtml2JsPreprocessor: {
      'moduleName': 'Templates',
      cacheIdFromPath: function(filepath) {
        return filepath.match(/\/WebContent\/modules\/common\/header\/.*\.html/);
      }
    },

I'm trying to load it by:

beforeEach(function() {
      module("Templates");
    });

Now i get the following errors:

Error: [$injector:modulerr] Failed to instantiate module Templates due to:
    Error: [$injector:nomod] Module 'Templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
    http://errors.angularjs.org/1.2.12/$injector/nomod?p0=Templates

Solution

  • I solved this in my unit tests by injecting the $templateCache into the test and then putting the html into the cache.

    http://plnkr.co/edit/btgYfiiRzacS6MfPFlbv?p=preview

    I researched a few different approaches, and we settled on putting the html into the directive.

    template: "<div>This is the template</div>"
    

    It makes it much easier to test as you no longer need to update the templateCache in the unit test, which is a pain in the ass and error prone when you have a big piece of html in your directive.