使用模板的测试指令 [英] Testing directives that uses templates

查看:24
本文介绍了使用模板的测试指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对使用 templateUrl 加载模板的指令进行单元测试?

How can i unit test directives that use templateUrl to load templates?

由于 $httpBackend 是一个模拟,它也不会加载模板.我希望能够使用类似

Since $httpBackend is a mock, it will not load templates either. I would like to be able to use something like

$httpBackend.whenGET(/^\/views\//).passThrough();

让它实际获取模板,但我还没有想出如何正确地做到这一点.

and let it actually get the templates, but I haven't figured out how to do this correctly.

我想我对如何对指令进行单元测试有些困惑.免责声明:我没有测试或使用茉莉花或睾丸的经验.

I think I have something confused regarding how to unit test directives. Disclaimer: I have no experience testing, or using jasmine nor testacular.

感谢任何帮助.

推荐答案

感谢 pkozlowski.opensource 带领我走向正确的方向!

Thanks to pkozlowski.opensource for leading me in the right direction!

对于想知道我是如何解决它的人:

For anyone wondering how I solved it:

  1. 添加https://npmjs.org/package/grunt-angular-templates到您的项目.
  2. 添加一个 grunt 构建任务,将所有模板编译成一个 js 文件.

这个 JS 文件现在将注册一个模块(名称可以在 gruntfile 中配置).

This JS file will now register a module (name can be configured in the gruntfile).

在依赖模板的所有测试中,您必须加载此模块.

In all your tests dependant on templates you have to load the this module.

示例测试:

'use strict';

describe('Component: comments', function() {
  beforeEach(module('studentportalenApp'), module('app.templates'));

  var element;

  it('should render an error message if type is not recognized', inject(function($rootScope, $compile) {
    element = angular.element('<comments></comments>');
    element = $compile(element)($rootScope);
    expect(element.html()).toBe('Comments directive type not recognized.');
  }));
});

小心使用与 app.templates 模块中定义的完全相同的 url 来获取您的视图.IE./views/而不是 views/,否则它将与模板缓存路径和请求的触发不匹配.

Be careful to get your views using the exact same url as defined in the app.templates module. I.e. /views/ and not views/, or else it will not match up with the template cache paths and fire of the request anyways.

这篇关于使用模板的测试指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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