Vin*_*ent 26 testing templates directive angularjs karma-runner
我无法使Karma适用于具有外部模板的指令.
这是我的业力配置文件:
preprocessors: {
'directives/loading/templates/loading.html': 'ng-html2js'
},
files: [
...
'directives/loading/templates/loading.html',
]
ngHtml2JsPreprocessor: {
prependPrefix: '/app/'
},
Run Code Online (Sandbox Code Playgroud)
在指令文件中:
...
templateUrl: '/app/directives/loading/templates/loading.html'
...
Run Code Online (Sandbox Code Playgroud)
在spec文件中:
describe('Loading directive', function() {
...
beforeEach(module('/app/directives/loading/templates/loading.html'));
...
});
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
由于以下原因无法实例化模块/app/directives/loading/templates/loading.html:错误:无模块:/app/directives/loading/templates/loading.html
如果我修改karma-ng-html2js-preprocessor的源代码来打印生成文件的结果,我得到:
angular.module('/app/directives/loading/templates/loading.html', []).run(function($templateCache) {
$templateCache.put('/app/directives/loading/templates/loading.html',
'<div ng-hide="hideLoading" class="loading_panel">\n' +
' <div class="center">\n' +
' <div class="content">\n' +
' <span ng-transclude></span>\n' +
' <canvas width="32" height="32"></canvas>\n' +
' </div>\n' +
' </div>\n' +
'</div>');
});
Run Code Online (Sandbox Code Playgroud)
所以似乎生成的JS文件是正确的但没有被karma加载......
另外,如果我使用--log-level debug,这里是与模板相关的行:
DEBUG [preprocessor.html2js]:处理"/home/rightink/public_html/bo2/master/web/app/directives/loading/templates/loading.html"
DEBUG [观察者]:已解决的文件:
Run Code Online (Sandbox Code Playgroud)/correct/path/to/the/app/directives/loading/templates/loading.html.js
我错过了什么吗?
谢谢,
Sig*_*gen 12
问题可能是file部分中指定的相对路径扩展为完整路径.
像directives/loading/templates/loading.html=>的东西/home/joe/project/angular-app/directives/loading/templates/loading.html
...然后,模板将在其完整路径中注册.
解决方案是配置ng-html2js预处理器以删除模板路径的绝对部分.例如,在karma.conf.js文件中添加stripPrefix指令,如下所示:
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: '.*/project/angular-app/'
prependPrefix: '/app/'
}
Run Code Online (Sandbox Code Playgroud)
请注意,stripPrefix是一个正则表达式.
sca*_*rlz 11
您可以让预处理器将模板缓存到模块,然后可以在测试之前将模板包含在模块中:
karma.conf.js
files: [
...
'app/**/*.html'
],
preprocessors: {
'app/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
},
Run Code Online (Sandbox Code Playgroud)
指令文件
...
templateUrl: 'app/path-to-your/template.html',
...
Run Code Online (Sandbox Code Playgroud)
spec文件
describe('My directive', function() {
beforeEach(module('templates'));
...
});
Run Code Online (Sandbox Code Playgroud)
这可能不是您的确切问题,但在我们的应用程序中,我们需要将以下内容添加到 karma.conf.js:
ngHtml2JsPreprocessor: {
cacheIdFromPath: function(filepath) {
return '/vision/assets/' + filepath;
}
}
Run Code Online (Sandbox Code Playgroud)
相应的预处理器设置如下所示:
preprocessors: {
'views/**/*.html': 'html2js'
},
Run Code Online (Sandbox Code Playgroud)
我的理解是,这是由于在指定模板时在 AngularJS 中使用绝对 URL - 运行测试时重写了哪个业力?
无论如何希望这会有所帮助。