如果这是一个单元测试,您将无法访问$httpBackend.passthrough()。这仅在 ngMock2E2 中可用,用于端到端测试。我同意涉及ng-html2js(以前称为html2js)的答案,但我想在这里扩展它们以提供完整的解决方案。
为了呈现你的指令,Angular 使用$http.get() 从templateUrl 获取你的模板。因为这是单元测试并且加载了angular-mocks,所以angular-mocks 拦截了对$http.get() 的调用并给你Unexpected request: GET 错误。您可以尝试找到绕过它的方法,但使用 Angular 的 $templateCache 预加载模板要简单得多。这样,$http.get() 甚至不会成为问题。
这就是ng-html2js preprocessor 为您做的事情。要让它工作,首先安装它:
$ npm install karma-ng-html2js-preprocessor --save-dev
然后通过在karma.conf.js 中添加/更新以下字段来配置它
{
files: [
//
// all your other files
//
//your htmp templates, assuming they're all under the templates dir
'templates/**/*.html'
],
preprocessors: {
//
// your other preprocessors
//
//
// tell karma to use the ng-html2js preprocessor
"templates/**/*.html": "ng-html2js"
},
ngHtml2JsPreprocessor: {
//
// Make up a module name to contain your templates.
// We will use this name in the jasmine test code.
// For advanced configs, see https://github.com/karma-runner/karma-ng-html2js-preprocessor
moduleName: 'test-templates',
}
}
最后,在您的测试代码中,使用您刚刚创建的test-templates 模块。只需将test-templates 添加到您通常在beforeEach 中进行的模块调用中,如下所示:
beforeEach(module('myapp', 'test-templates'));
从这里开始应该一帆风顺。要更深入地了解这个和其他指令测试场景,请查看this post