angularjs - 在单元测试中使用 passThrough 进行 Angular 测试

标签 angularjs angularjs-directive directive

我正在尝试在 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>");

但我真的想简单地返回实际文件,并且同步执行,所以等待、延迟对象等没有问题。如何做到这一点?

最佳答案

我现在使用 https://github.com/karma-runner/karma-ng-html2js-preprocessor .它的作用是读取您使用的所有模板,将它们转换为 Angular 模板,并将它们设置在 $templateCache 上,因此当您的应用需要它们时,它将从缓存中检索它们,而不是从服务器请求它们。

在我的 karma 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'
},

然后在测试中,像
// Load templates
angular.mock.module('templates');

它有效!

关于angularjs - 在单元测试中使用 passThrough 进行 Angular 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320302/

相关文章:

angularjs - 基于属性的指令中的动态模板?

javascript - 如何从 Isolate Scope 指令调用 Controller 方法?

javascript - 如何在 ng-option 中使用空白值,而不是 NULL

javascript - Angular 在 Controller 中使用 Json 数据

jquery - 使用 $routeProvider 时 Angular 应用程序中的 dataTables jQuery 插件

AngularJS:指令隔离范围 - 范围变量未定义

html - 如何在 AngularJS 自定义指令中对 Angular 移动父 <div>

javascript - Angularjs 1.30 密码验证。验证确认密码匹配

javascript - 无法通过 systemjs 导入 ng-bootstrap

javascript - AngularJS - 使用 ng-repeat 的动态指令