AngularJS Karma测试:意外请求:GET.template.html

4
我正在尝试为我的AngularJS应用程序设置karma测试,但是我总是失败。我已经按照这里的所有步骤进行了操作,但我感觉ng-html2js预处理器没有正常工作。我总是收到以下消息:

错误:意外请求:GET js/templates/my-template.template.html

这是我的代码结构

code structure

这是我的测试结构

enter image description here

我正在尝试测试的指令是:

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

我的karma配置如下:

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)
}

而我的Spec.js文件如下:

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个回答

1
在您的beforeEach函数中添加一个用于指令HTML模板的模拟模板。使用$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);
    });
});

2
ng-html2js不是为了避免这样做吗?我的指令HTML可能相当大,我不想把它全部粘贴在那里。 - user3083022
ng-html2js 生成的文件在哪个文件夹中? - Gonzalo Pincheira Arancibia
这就是我一直在问自己的问题。我该如何找到答案? - user3083022
我假设 template.html.js 已经在你的项目中生成。你应该将这个文件添加到 karma.conf.js 的 files 属性中。 - Gonzalo Pincheira Arancibia
没有 template.html.js。 - user3083022
显示剩余2条评论

1

我想我明白了。解决方案在 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'
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接