AngularJS Karma Test: Unexpected request: GET.template.html

2.4k Views Asked by At

I'm trying to set up karma tests for my AngularJS app but I am somehow failing constantly. I have followed all the steps here but I have the feeling the ng-html2js preprocessor is not working properly. I am always getting the following message:

Error: Unexpected request: GET js/templates/my-template.template.html

Here's my code structure

code structure

And here my test structure

enter image description here

The directive I am trying to test is:

angular
    .module('myapp')
    .directive('myDirective', ['myService', function (myService) {
        return {
            restrict: 'E',
            templateUrl: 'js/templates/my-template.template.html',
            scope: {},
            link: function (scope) {
            }
        }
    }]);

My karma conf looks like this:

module.exports = function (config) {
config.set({

    basePath: '../../',

    frameworks: ['jasmine'],


    files: [
        //some omitted like angular and so on...
        'main/resources/static/**/*.js',
        '**/*.html',
        'test/js/**/*Spec.js'
    ],

    preprocessors: {
        '**/*.html': ['ng-html2js']
    },

    ngHtml2JsPreprocessor: {
        moduleName: 'templates'
    }
... (more default stuff omitted)
}

and mySpec.js like this:

describe('directive', function () {
    'use strict';

    beforeEach(module('myapp'));
    beforeEach(module('templates'));

    var elm,
        scope;

    beforeEach(inject(function ($rootScope, $compile) {
        elm = angular.element(
        '<my-directive>' +
        '</my-directive>');

        scope = $rootScope.$new();

        $compile(elm)(scope);
        scope.$digest();
    }));

    describe('Does something', function () {
        console.log('test');
        expect(true).toBe(true);
    });
});
2

There are 2 best solutions below

0
On BEST ANSWER

I think I got it. Solution was in karma.conf.js:

ngHtml2JsPreprocessor: {
    cacheIdFromPath: function (filepath) {
        //The suggested filepath.strip would through an error
        var cacheId = filepath.replace('main/resources/static/', '');
        return cacheId;
    },
    moduleName: 'templates'
}
7
On

Add in your beforeEach function a mock template for your html template of your directive. Use $templateCache:

describe('directive', function () {
    'use strict';

    beforeEach(module('myapp'));
    beforeEach(module('templates'));

    var elm,
        scope;

    beforeEach(inject(function ($rootScope, $compile, $templateCache) {


        $templateCache.put('js/templates/my-template.template.html','HTML_OF_YOUR_DIRECTIVE');

        elm = angular.element(
        '<my-directive>' +
        '</my-directive>');

        scope = $rootScope.$new();

        $compile(elm)(scope);
        scope.$digest();
    }));

    describe('Does something', function () {
        console.log('test');
        expect(true).toBe(true);
    });
});