Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 nativeElement attribute testing in App component

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?

like image 587
jspriggs Avatar asked Dec 20 '16 16:12

jspriggs


2 Answers

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);
like image 164
Ben Hernandez Avatar answered Oct 05 '22 03:10

Ben Hernandez


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
like image 25
Vijay Barot Avatar answered Oct 05 '22 02:10

Vijay Barot