我无法让 Karma 为具有外部模板的指令工作。
这是我的 karma 配置文件:
preprocessors: {
'directives/loading/templates/loading.html': 'ng-html2js'
},
files: [
...
'directives/loading/templates/loading.html',
]
ngHtml2JsPreprocessor: {
prependPrefix: '/app/'
},
在指令文件中:
...
templateUrl: '/app/directives/loading/templates/loading.html'
...
在规范文件中:
describe('Loading directive', function() {
...
beforeEach(module('/app/directives/loading/templates/loading.html'));
...
});
我收到以下错误:
Failed to instantiate module /app/directives/loading/templates/loading.html due to: Error: No module: /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>');
});
所以看起来生成的JS文件是正确的但是没有被karma加载...
此外,如果我使用 --log-level 调试,这里是与模板相关的行:
DEBUG [preprocessor.html2js]: Processing "/home/rightink/public_html/bo2/master/web/app/directives/loading/templates/loading.html"
DEBUG [watcher]: Resolved files:
/correct/path/to/the/app/directives/loading/templates/loading.html.js
我错过了什么吗?
谢谢,
最佳答案
问题可能是 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/'
}
请注意,stripPrefix 是一个正则表达式。
关于templates - AngularJS + Karma + Ng-html2js => 无法实例化模块 ...html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19360083/