Wil*_*der 15 directive angularjs angularjs-directive
我正试图在Angular中测试一个指令,但是我无法使用相应的模板.
该指令列出了templateUrl,如下所示
templateUrl: 'directives/listview/view.html'
Run Code Online (Sandbox Code Playgroud)
现在,当我写任何单元测试时,我得到了
Error: Unexpected request: GET directives/listview/view.html
Run Code Online (Sandbox Code Playgroud)
所以我必须使用$ httpBackend并回复一些明智的事情
httpBackend.whenGET('directives/listview/view.html').respond("<div>som</div>");
Run Code Online (Sandbox Code Playgroud)
但实际上我想简单地返回实际文件,并同步执行,因此等待,延迟对象等没有问题.如何做到这一点?
Wil*_*der 13
我现在使用https://github.com/karma-runner/karma-ng-html2js-preprocessor.它的作用是读取您使用的所有模板,将它们转换为Angular模板,并将它们设置在$ templateCache上,因此当您的应用程序需要它们时,它将从缓存中检索它们,而不是从服务器请求它们.
在我的业力conf文件中
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'
},
Run Code Online (Sandbox Code Playgroud)
然后在测试中,喜欢
// Load templates
angular.mock.module('templates');
Run Code Online (Sandbox Code Playgroud)
它的工作原理!
Ben*_*esh 10
如果不这样做,$ browser服务器模拟将在whenGET调用时不被实例化,并且返回值将不会设置该passThrough函数
beforeEach(function() {
module('yourModule');
module('ngMockE2E'); //<-- IMPORTANT!
inject(function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('somefile.html').passThrough();
});
});
Run Code Online (Sandbox Code Playgroud)
有问题的源代码是$ 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;
}
Run Code Online (Sandbox Code Playgroud)