'错误:意外请求'在Karma Angular Unit Test期间

时间:2014-05-02 13:17:13

标签: javascript angularjs unit-testing jasmine karma-runner

运行grunt karma时,对其中一个指令的测试在尝试获取模板时失败。我使用ng-html2js作为预处理器。这是我的一些karma.conf.js

plugins: ['karma-chrome-launcher',
          'karma-jasmine',
          'ng-html2js',
          'karma-ng-html2js-preprocessor'],

preprocessors: {
  'app/scripts/directives/**/*.html': 'ng-html2js'
},

ngHtml2JsPreprocessor: {
  moduleName: 'templates'
}

在我的测试中,我有以下内容:

'use strict';

describe('Directive: myDirective', function () {

  // load the directive's module
  beforeEach(module('myApp'));
  beforeEach(module('templates'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));

  it('should not show search area initially', inject(function ($compile) {
    element = angular.element('<navbar></navbar>');
    element = $compile(element)(scope);
    scope.$digest();
    expect(element.find('.myClass').hasClass('myClass')).toBe(true);
  }));
});

当我进行测试时,我得到了

Error: Unexpected request: GET /scripts/directives/myDirective/myDirective.html

预处理器似乎没有正确地注入模板的javascript版本。

我也尝试在beforeEach(module(''));中使用模板的路径,但会导致错误:

Error: [$injector:modulerr] Failed to instantiate module...

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:9)

我遇到了同样的问题。确保您具有完全匹配的文件。打开Goog​​le Chrome控制台并检查文件路径是否完全相同。

enter image description here

在上面的例子中,我不得不添加&#34; /&#34;在ngHtml2JsPreprocessor.stripPrefix中的字符串,它工作。 所以我想对于Yeoman,你应该使用

ngHtml2JsPreprocessor: {
  moduleName: 'templates',
  stripPrefix: 'app/' //add a slash
}

答案 1 :(得分:0)

由于我使用Yeoman工具来构建项目,我需要在stripPrefix文件的ngHtml2JsPreprocessor选项中添加karma.conf.js

ngHtml2JsPreprocessor: {
  moduleName: 'templates',
  stripPrefix: 'app'
}
相关问题