Angular2 testing - Get element by Id

Angular

Angular 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionohadinhoView Question on Stackoverflow
Solution 1 - AngularJ J BView Answer on Stackoverflow
Solution 2 - Angularhazan kazimView Answer on Stackoverflow
Solution 3 - AngularVijay BarotView Answer on Stackoverflow