我正在尝试在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>");
但实际上我只想简单地返回实际文件,并同步执行,因此等待,延迟对象等没有问题。怎么做?
答案 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)
如果不这样做,则在调用whenGET
时不会实例化$浏览器服务模拟,并且返回值不会设置passThrough
函数
beforeEach(function() {
module('yourModule');
module('ngMockE2E'); //<-- IMPORTANT!
inject(function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('somefile.html').passThrough();
});
});
有问题的源代码在$ 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;
}