AngularJS + Karma + Ng-html2js => Failed to instantiate module …html

后端 未结 4 890
深忆病人
深忆病人 2021-02-02 09:28

I can\'t make Karma working for directives that have external templates.

Here is my karma configuration file :

pr         


        
相关标签:
4条回答
  • 2021-02-02 10:05

    I'm in the process of learning AngularJS and ran into the same problem. I have no idea why but changing the port in karma.conf.js fixed it for me.

    module.exports = function(config){
      config.set({
    
        ...
    
        port: 9877,
    
        ...
    
      });
    };
    

    Edit:

    After a bit more testing I found that the problem was only happening on Chrome, and was resolved by explicitly clearing all of the browser history (Ctrl + F5 didn't work).

    0 讨论(0)
  • 2021-02-02 10:22

    You can have the pre-processor cache your templates to a module, which can then be included prior to your tests:

    karma.conf.js

    files: [
      ...
      'app/**/*.html'
    ],
    
    preprocessors: {
      'app/**/*.html': ['ng-html2js']
    },
    
    ngHtml2JsPreprocessor: {
       moduleName: 'templates'
    },
    

    directive file

    ...
    templateUrl: 'app/path-to-your/template.html',
    ...
    

    spec file

    describe('My directive', function() {
    
      beforeEach(module('templates'));
      ...
    });
    
    0 讨论(0)
  • 2021-02-02 10:24

    The problem may be that relative paths specified in file section get expanded to full ones.

    Something like directives/loading/templates/loading.html => /home/joe/project/angular-app/directives/loading/templates/loading.html

    ... and then, templates get registered with theirs full paths.

    The solution is to configure the ng-html2js preprocessor to remove the absolute part of the template paths. For instance, in the karma.conf.js file add the stripPrefix directive like this :

    ngHtml2JsPreprocessor: {
        // strip this from the file path
        stripPrefix: '.*/project/angular-app/'
        prependPrefix: '/app/'
    }
    

    Note that stripPrefix is a regexp.

    0 讨论(0)
  • 2021-02-02 10:26

    This may not be your exact issue, but in our application we needed to add the following to karma.conf.js:

    ngHtml2JsPreprocessor: {
        cacheIdFromPath: function(filepath) {
            return '/vision/assets/' + filepath;
        }
    }
    

    The corresponding preprocessors setting looks like:

    preprocessors: {
        'views/**/*.html': 'html2js'
    },
    

    My understanding was that this was due to using absolute URLs in AngularJS when specifying templates - which karma was rewriting when running tests?

    Anyway hope this helps.

    0 讨论(0)
提交回复
热议问题