简体   繁体   中英

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

The Karma way is to load the template html dynamically into $templateCache. You could just use html2js karma pre-processor, as explained here

This boils down to adding templates '*.html' to your files in the conf.js file as well

preprocessors = {
  '*.html': 'html2js'
};

and use

beforeEach(module('..'));

beforeEach(module('...html', '...html'));

into your js testing file

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM