element accessed via debugElement.nativeElement?
import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; @Component({ selector: 'app-greet', template: `<p>Hello, {{name}}!</p>` }) class GreetComponent { name = 'Alice'; } // Test setup let fixture: ComponentFixture<GreetComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [GreetComponent] }).compileComponents(); fixture = TestBed.createComponent(GreetComponent); fixture.detectChanges(); }); const pElement = fixture.debugElement.query(By.css('p')).nativeElement; const textContent = pElement.textContent.trim();
The component initializes name as 'Alice'. After fixture.detectChanges(), Angular updates the template, so the <p> element shows "Hello, Alice!".
The selector button.submit-btn matches a <button> element with class submit-btn. The other options either misuse directive selectors or incorrect CSS selectors.
If query returns null because the element is missing, then button is null. Accessing button.nativeElement causes a TypeError.
{{count}}
` }) class CounterComponent { count = 0; increment() { this.count++; } } // Test const fixture = TestBed.createComponent(CounterComponent); fixture.detectChanges(); const button = fixture.debugElement.query(By.css('button')); button.triggerEventHandler('click', null); fixture.detectChanges(); const displayedCount = fixture.componentInstance.count;The increment() method increases count by 1 when the button is clicked. After triggering the click and running change detection, count is 1.
fixture.debugElement over fixture.nativeElement when querying elements in Angular tests?debugElement wraps native DOM elements and adds Angular-specific methods like querying by directives, triggering event handlers, and accessing component instances. nativeElement is just the raw DOM node without these features.