AngularJS Karma 测试 : Unexpected request: GET. template.html

标签 angularjs jasmine karma-runner karma-jasmine ng-html2js

我正在尝试为我的 AngularJS 应用程序设置 karma 测试,但不知何故我不断失败。
我已按照所有步骤操作 here但我感觉 ng-html2js 预处理器工作不正常。我总是收到以下消息:

Error: Unexpected request: 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 conf 如下所示:
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)
}

和 mySpec.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);
    });
});

最佳答案

在你的 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);
    });
});

关于AngularJS Karma 测试 : Unexpected request: GET. template.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37888004/

相关文章:

javascript - api返回404,但记录已插入数据库

javascript - Karma/Jasmine 规范 -- 预期 { } 等于 { }

angular - 分组测试结果 : Karma/Protractor integration with Jenkins

angularjs - 如何使用 Restangular 通过 GET 发送参数数组

javascript:通过增加 objectKeys 值来更新对象

javascript - 运行 jasmine 测试用例时未命中异步调用

javascript - 无法在 Jasmine 中调用 Javascript 函数

angular - 如何在测试中模拟 Angular 4.3 httpClient 的错误响应

angularjs - 用于检查元素列表的 Angular e2e 测试

javascript - 使用 Protractor 测试 Chart.js Canvas