在单元测试中使用 passThrough 进行角度测试 [英] Angular testing using passThrough in unit testing

查看:28
本文介绍了在单元测试中使用 passThrough 进行角度测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 中测试指令,但无法使相应的模板正常工作.

I'm trying to test a Directive in Angular, but I can't get the corresponding template to work.

该指令像这样列出了 templateUrl

The directive lists the templateUrl like so

templateUrl: 'directives/listview/view.html'

现在当我编写任何单元测试时,我得到

Now when I write any unit-test, I get

Error: Unexpected request: GET directives/listview/view.html

所以我必须使用 $httpBackend 并用像

So I have to use the $httpBackend and respond with something sensible like

httpBackend.whenGET('directives/listview/view.html').respond("<div>som</div>");

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

But really I want to simply return the actual file, and also do it synchronously, so there's no issues with waits, deferred objects etc. How to do that?

推荐答案

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

I now use https://github.com/karma-runner/karma-ng-html2js-preprocessor. What it does is reading in all the templates that you use, convert them to Angular templates, and set them on the $templateCache, so when your app needs them, it will retrieve them from cache, and not request them from the server.

在我的 karma conf 文件中

In my karma conf file

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');

它有效!

这篇关于在单元测试中使用 passThrough 进行角度测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆