Angular2 testing - Get element by Id

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

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


You can also use by.css

de = fixture.debugElement.query(By.css('#theid'));

Tags:

Angular