在单元测试中使用passThrough进行角度测试

时间:2013-10-11 14:10:35

标签: angularjs angularjs-directive directive

我正在尝试在Angular中测试指令,但我无法使相应的模板起作用。

该指令列出了templateUrl,如此

templateUrl: 'directives/listview/view.html'

现在当我写任何单元测试时,我得到了

Error: Unexpected request: GET directives/listview/view.html

所以我必须使用$ httpBackend并回复一些像

这样明智的东西
httpBackend.whenGET('directives/listview/view.html').respond("<div>som</div>");

但实际上我只想简单地返回实际文件,并同步执行,因此等待,延迟对象等没有问题。怎么做?

2 个答案:

答案 0 :(得分:13)

我现在使用https://github.com/karma-runner/karma-ng-html2js-preprocessor。它所做的是读取您使用的所有模板,将它们转换为Angular模板,并将它们设置在$ templateCache上,因此当您的应用需要它们时,它将从缓存中检索它们,而不是从服务器请求它们。 / p>

在我的业力配置文件中

files: [
    // templates
    '../**/*.html'
],

preprocessors : {
  // generate js files from html templates
  '../**/*.html': 'ng-html2js'
},

ngHtml2JsPreprocessor: {
    // setting this option will create only a single module that contains templates
    // from all the files, so you can load them all with module('templates')
    moduleName: 'templates'
},

然后在测试中,确实喜欢

// Load templates
angular.mock.module('templates');

它有效!

答案 1 :(得分:10)

请确保在beforeEach

中包含ngMockE2E模块

如果不这样做,则在调用whenGET时不会实例化$浏览器服务模拟,并且返回值不会设置passThrough函数

beforeEach(function() {
   module('yourModule');
   module('ngMockE2E'); //<-- IMPORTANT!

   inject(function(_$httpBackend_) {
    $httpBackend = _$httpBackend_;
    $httpBackend.whenGET('somefile.html').passThrough();
   });
});

angular-mocks.js中设置此位置的位置:

有问题的源代码在$ httpBackend mock的when函数中:

function (method, url, data, headers) {
  var definition = new MockHttpExpectation(method, url, data, headers),
      chain = {
        respond: function(status, data, headers) {
          definition.response = createResponse(status, data, headers);
        }
      };

  if ($browser) {
    chain.passThrough = function() {
      definition.passThrough = true;
    };
  }
  definitions.push(definition);
  return chain;
}