Angular 50: Testing Components
easy⏱ 5 mincourseangular
TestBed configures an isolated testing module
TestBed.configureTestingModule({ imports: [LikeButtonComponent] }) works because standalone components are just importable classes — no declarations array needed, unlike the old NgModule-based testing setup. TestBed.createComponent(...) instantiates it inside a ComponentFixture, and fixture.detectChanges() runs an initial change-detection pass.
TestBed.configureTestingModule({ imports: [LikeButtonComponent] });
const fixture = TestBed.createComponent(LikeButtonComponent);
fixture.detectChanges();
Querying the DOM with By.css
fixture.debugElement.query(By.css('button')) finds an element the same way a browser querySelector would, but returns a DebugElement with extra testing helpers like triggerEventHandler(...), which simulates a bound event — here, the (click) handler — without a real user.
const button = fixture.debugElement.query(By.css('button'));
button.triggerEventHandler('click', null);
fixture.detectChanges();
Signals make assertions trivial
Because liked is a signal, there's no async/whenStable() dance needed for this kind of state change — updating a signal and calling fixture.detectChanges() synchronously re-renders the template, so the very next assertion sees the new DOM.