jspriggs
jspriggs

Reputation: 403

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?

Upvotes: 9

Views: 19968

Answers (3)

Amin Setayeshfar
Amin Setayeshfar

Reputation: 908

this is how I could finally make it work

const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p

const attributeValue = element['attribute name']; // for example src, href

Upvotes: 1

Vijay Barot
Vijay Barot

Reputation: 352

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

Upvotes: 1

Ben Hernandez
Ben Hernandez

Reputation: 857

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);

Upvotes: 8

Related Questions