Angular2 testing - Get element by Id
AngularAngular Problem Overview
I'm writing an Angular2 test component and i've noticed this line in the tutorials:
de = fixture.debugElement.query(By.css('h1'));
de
is defined as DebugElement
type.
How can I get DebugElement
by id?
That may seem extremely simple but I can't find any direction in the docs.
Angular Solutions
Solution 1 - Angular
You can also use by.css
de = fixture.debugElement.query(By.css('#theid'));
Solution 2 - Angular
const fixture = TestBed.createComponent(DashboardComponent);
const compiled = fixture.debugElement.nativeElement;
-
using id
expect(compiled.querySelector('#from').textContent).toContain('From Date');
-
using css
expect(compiled.querySelector('.from').textContent).toContain('From Date');
Solution 3 - Angular
You can use following syntax to get an attribute value from an HTML element:
To retrieve an HTML element:
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p
To get an attribute value from that element:
const attributeValue = element.attributeName // like textContent/href