我有一个我正在研究的Angular 2应用程序,出于与遗留代码的一些兼容性原因,需要通过应用程序组件上使用的属性获取一些信息.例如,启动angular 2应用程序的html将如下所示:
<myApp id="xyz" areaDone="true" value="" requestID="abc"> Loading ... </myApp>
但是,当我尝试围绕应该根据这些属性的存在和值发生的行为编写一些单元测试时,它们是null / undefined.
let native = this.elementRef.nativeElement; this.requestID= native.getAttribute("requestID");
解决方法
您可以调用this.elementRef.nativeElement.attribute,它将返回属性的NamedNodeMap(
http://www.w3schools.com/jsref/prop_node_attributes.asp).
从NamedNodeMaps获取东西的语法并不可怕,这是我在我的一个测试中从d3对象获取x1属性
const nodeAttributes = compiled.querySelector('#temp-draggable-link-line').attributes as NamedNodeMap; expect(nodeAttributes.getNamedItem('x1').value).toEqual(200);