在单元测试中访问编译模板 [英] Accessing compiled template in unit tests
问题描述
大部分 Angular 教程都谈到使用 Protractor 的端到端测试来测试编译后的模板是否按预期出现.我想知道是否可以通过单元测试来做到这一点.
Most of the Angular tutorials talk about using end to end tests with Protractor to test whether the compiled template came out as expected. I'm wondering if it's possible to do this with unit tests at all.
大多数讨论在单元测试中引用 HTML 代码的教程都描述了在测试中编译您自己编写的代码,例如,以确保正确访问指令:
Most of the tutorials that do talk about referencing HTML code in unit tests describe compiling your own written code in the test, for example, to make sure a directive is being accessed correctly:
describe('some function', function () {
it('should do something', inject(function ($compile, $rootScope) {
var element = $compile('<div id = "foo" ng-hide = "somecondition">Bar</div>')($Scope);
$rootScope.digest();
//Search for a given DOM element and perform some test here
}));
});
但是假设我想测试实际模板文件中的代码.就像我想测试 ng-hide 是否设置成功一样.我希望能够执行以下操作:
But let's say I want to test the code in the actual template file. Like if I wanted to test whether ng-hide was successfully set. I want to be able to do something like:
describe('some function', function () {
it('should do something', function () {
//Get the div with ID 'foo' in the compiled template
var elm = $('#foo');
expect(elm.css('display')).toEqual('none');
});
});
当我这样做时这不起作用.elm
被设置为一些 HTML/Javascript 代码,但不是模板的代码,并且 elm.css('display')
返回未定义.
This doesn't work when I do it. elm
gets set to some HTML/Javascript code, but not the template's code, and elm.css('display')
comes back as undefined.
有没有办法使用 Jasmine/Angular 设置对此进行单元测试?
Is there a way to unit test this with the Jasmine/Angular set up?
推荐答案
使用 ng-html2js 以便它们在您的测试中可用.
Load your HTML templates into Angular's $templateCache
using ng-html2js so that they are available in your tests.
在您的测试中检索您的特定模板:
Retrieve your specific template in your tests:
var template = $templateCache.get('my/template.html');
将模板包装在一个更容易使用的 jqLite/jQuery 对象中:
Wrap the template in a jqLite/jQuery object that's easier to work it:
var element = angular.element(template);
然后您可以选择模板中的元素:
Then you can select elements within your template:
var fooEl = element.find('#foo');
对于断言,您不想测试 display: none
是否设置在元素上,而是测试 ng-hide
的内部实现.您可以相信 Angular 团队有他们自己的测试,涵盖设置 CSS 属性.相反,您想测试您是否正确编写了模板,因此更适合测试元素上是否存在 ng-hide
属性,并且为它提供了正确的范围属性绑定到:
For asserting, you don't want to test that display: none
is set on the element, that's testing the internal implementations of ng-hide
. You can trust that the Angular team have their own tests that cover setting CSS properties. Instead, you want to test that you've written the template correctly, so it's more appropriate test for the existence of the ng-hide
attribute on the element, and that it is supplied with the right scope property to bind to:
expect(fooEl.attr('ng-hide')).toBe('isFooElHidden');
这篇关于在单元测试中访问编译模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!