62

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.

3 Answers 3

99

You can also use by.css

de = fixture.debugElement.query(By.css('#theid'));
Sign up to request clarification or add additional context in comments.

11 Comments

I'm getting: TypeError: platform_browser_1.By.id is not a function
What does the call to .debugElement.nativeElement return?
I was able to get the same results using .debugElement instead of .debugElement.nativeElement ... ie the return was a button that had a disabled attribute. Thank you for this answer as well, saved my day
@AdamHughes Yes, that's how I had it, if you review the revision here stackoverflow.com/posts/41399194/revisions you will see that. I'm looking into if there is a prefered method.
If anyone gets tripped by the By is not defined error, this import might help: import { By } from "@angular/platform-browser";
|
28
  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');

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.