我正在开发一个Angular 2应用程序,出于与遗留代码的兼容性原因,它需要通过应用程序组件上使用的属性来获取一些信息。例如,启动angular 2应用程序的html将如下所示:
<myApp id="xyz" areaDone="true" value="" requestID="abc"> Loading ... </myApp>然而,当我试图围绕基于这些属性的存在和值而应该发生的行为编写一些单元测试时,它们是空的/未定义的。
为了获得这些值,我们只需像这样在构造函数中拉取它们:
let native = this.elementRef.nativeElement;
this.requestID= native.getAttribute("requestID");那么,有没有办法通过测试床/提供者来强制本机元素应该具有预期的属性呢?
发布于 2016-12-22 10:48:27
您可以调用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);发布于 2018-07-11 18:43:35
您可以使用以下语法从html元素获取属性值
//检索html元素
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p//从该元素获取属性值
const attributeValue = element.attributeName // like textContent/href发布于 2021-04-18 19:13:42
这就是我最终能让它工作的方式
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p
const attributeValue = element['attribute name']; // for example src, hrefhttps://stackoverflow.com/questions/41247554
复制相似问题