I have an Angular 2 app I'm working on, which for some compatibility reasons with legacy code, needs to get some information via attributes used on the app component. For example, the html that launches the angular 2 app would look like this:
<myApp id="xyz" areaDone="true" value="" requestID="abc"> Loading ... </myApp>
However, when I try to write some unit tests around the behavior that is supposed to occur based on the presence and value of these attributes, they are null/undefined.
To get the values, we are just pulling them in the constructor like this:
let native = this.elementRef.nativeElement;
this.requestID= native.getAttribute("requestID");
So, is there a way through the testbed/providers to force a native element that should have the expected attributes?
You can call this.elementRef.nativeElement.attribute
and that will return a NamedNodeMap (http://www.w3schools.com/jsref/prop_node_attributes.asp) of your attributes.
Syntax for getting stuff from NamedNodeMaps isn't terrible, this is me getting the x1 attributes from a d3 object in one of my tests
const nodeAttributes = compiled.querySelector('#temp-draggable-link-line').attributes as NamedNodeMap;
expect(nodeAttributes.getNamedItem('x1').value).toEqual(200);
You can use following syntax to get attribute value from html element
//to retrieve html element
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p
//get attribute value from that element
const attributeValue = element.attributeName // like textContent/href
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With