A. *_*uff 4 unit-testing jasmine angularjs
大多数Angular教程都讨论了使用Protractor进行端到端测试来测试编译模板是否按预期出现.我想知道是否有可能完成单元测试.
大多数关于在单元测试中引用HTML代码的教程都描述了在测试中编译自己编写的代码,例如,以确保正确访问指令:
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
}));
});
Run Code Online (Sandbox Code Playgroud)
但是,假设我想测试实际模板文件中的代码.就像我想测试ng-hide是否成功设置一样.我希望能够做到这样的事情:
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');
});
});
Run Code Online (Sandbox Code Playgroud)
当我这样做时,这不起作用.elm设置为一些HTML/Javascript代码,但不是模板的代码,并elm.css('display')返回未定义.
有没有办法用Jasmine/Angular设置单元测试?
$templateCache使用ng-html2js将HTML模板加载到Angular中,以便它们在测试中可用.
在测试中检索您的特定模板:
var template = $templateCache.get('my/template.html');
Run Code Online (Sandbox Code Playgroud)
将模板包装在更容易使用的jqLite/jQuery对象中:
var element = angular.element(template);
Run Code Online (Sandbox Code Playgroud)
然后,您可以选择模板中的元素:
var fooEl = element.find('#foo');
Run Code Online (Sandbox Code Playgroud)
对于断言,您不希望测试display: none在元素上设置的那个,即测试内部实现ng-hide.您可以相信Angular团队有自己的测试,涵盖设置CSS属性.相反,您要测试您是否正确编写了模板,因此更适合测试ng-hide元素上属性的存在,并且它提供了正确的scope属性以绑定到:
expect(fooEl.attr('ng-hide')).toBe('isFooElHidden');
Run Code Online (Sandbox Code Playgroud)