Where is my template in karma-ng-html2js-preprocessor?

karma-ng-html2js-preprocessor is great when it works, but it can be fiddly to line up your template URL with the key it stores in $templateCache.

karma-ng-html2js-preprocessor is used for Karma testing when you want an Angular html template to be loaded in the cache.  This is helpful because it will prevent $httpBackend from complaining when your directive tries to use $http to get your template html.  Instead, the directive will find the template in the cache and skip the $http call.

But… the problem is that it can be difficult to figure out what is wrong when things are not set up just right.  The biggest problem I’ve found is actually seeing what is inside the $templateCache.  Often, the key in the cache (which will be the URL for your template) will not have a forward-slash (“/”) in front, or will have a problem with case being different from what was loaded.

The problem with examining $templateCache is that it doesn’t expose its contents as a property.  You have to ALREADY KNOW the key to see if it is inside the cache.

Fortunately, if you are using WebStorm, you can get past this.  WebStorm will show you the function scope of an object constructor.  So you can do this:

karma-ng-html2js-preprocessor

If you do not use webstorm, you can place a hack in your karma config:

preprocessors: {
       "**/*.html": ['ng-html2js']
},
ngHtml2JsPreprocessor: {
    cacheIdFromPath: function(filepath) {
        debug("ng-html2j filepath: " + filepath);
        return filepath;
    },
    prependPrefix: '/',
    moduleName: 'my.templates'
},

Notice the “moduleName” property in the config above.  Another thing I often forget is to call my template module in the “beforeEach” method for Jasmine/Mocha:

beforeEach(function(){
   module("my.templates");
}

Occasionally, I might also forget to tell Karma (in my karma config file) it can serve the html files:

files: [
   { pattern: 'bower_components/angular/angular.js', watched: false, included: true, served: true },
   'src/**/*.html',
   '../tests/clientUnit/*.js'
],