问题描述
大部分的角教程说说使用端到端用量角器测试来测试编译模板是否出来了预期。我不知道是否有可能在所有的单元测试来做到这一点。
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 code教程的描述编译你自己写的code在测试中,例如,以确保指令是否被正确访问:
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
}));
});
但是,让我们说,我想测试在实际的模板文件中的code。就像如果我想测试纳克隐藏是否设置成功。我希望能够做一些事情,如:
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');
});
});
当我这样做,这是行不通的。 榆树
被设置为一些HTML / Javascript code,但没有模板的code和 elm.css('显示器')
回来为未定义。
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.
有没有办法进行单元测试此与茉莉花/角设置?
Is there a way to unit test this with the Jasmine/Angular set up?
推荐答案
装入HTML模板角的 $ templateCache
使用的,使他们在测试中使用。
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');
有关主张,你不想来测试显示:无
设置的元素,这是测试的内部实现 NG-隐藏
。你可以信任的角度队有他们自己的测试,涵盖设置CSS属性。相反,你想测试你编写正确的模板,所以它的元素的 NG-隐藏
属性的存在,更合适的测试,并且是用正确的范围属性提供绑定到:
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');
这篇关于访问编译模板单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!