Bird
0
0

In this test code, why does fixture.debugElement.query(By.css('input')) return null?

medium📝 Debug Q6 of 15
Angular - Testing
In this test code, why does fixture.debugElement.query(By.css('input')) return null?
const fixture = TestBed.createComponent(MyComponent);
// Missing fixture.detectChanges()
const input = fixture.debugElement.query(By.css('input'));
ABecause query() requires a nativeElement, not DebugElement
BBecause the input element does not exist in the component template
CBecause detectChanges() was not called, the template is not rendered yet
DBecause By.css('input') is an invalid selector
Step-by-Step Solution
Solution:
  1. Step 1: Effect of missing detectChanges()

    Without detectChanges(), Angular does not render the template, so no elements exist in debugElement.
  2. Step 2: Query returns null

    Querying for 'input' returns null because the element is not present in the unrendered template.
  3. Final Answer:

    Because detectChanges() was not called, the template is not rendered yet -> Option C
  4. Quick Check:

    Missing detectChanges() means no elements found [OK]
Quick Trick: Always call detectChanges() before querying elements [OK]
Common Mistakes:
  • Assuming query() needs nativeElement
  • Thinking selector is invalid
  • Assuming element is missing in template

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes