【问题标题】:'Error: Unexpected request' during Karma Angular Unit TestKarma Angular 单元测试期间的“错误:意外请求”
【发布时间】:2014-06-19 04:42:30
【问题描述】:

在运行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...

我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    我遇到了同样的问题。确保您有完全匹配的文件。打开谷歌浏览器控制台,检查文件路径是否完全一致。

    在上面的示例中,我必须在 ngHtml2JsPreprocessor.stripPrefix 中添加一个“/”字符串并且它起作用了。 所以我想对于 Yeoman,你应该使用

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

    【讨论】:

      【解决方案2】:

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

      ngHtml2JsPreprocessor: {
        moduleName: 'templates',
        stripPrefix: 'app'
      }
      

      【讨论】:

        猜你喜欢
        • 2015-07-08
        • 2014-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-28
        • 1970-01-01
        • 2023-03-12
        相关资源
        最近更新 更多