`,
})
export class CounterComponent {
count = 0;
increment() { this.count++; }
}
// counter.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CounterComponent], // standalone component goes in imports
}).compileComponents();
fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges(); // initial render
});
it('starts at Count: 0', () => {
expect(fixture.nativeElement.textContent).toContain('Count: 0');
});
it('increments when the +1 button is clicked', () => {
const button = fixture.nativeElement.querySelector('button');
button.click();
fixture.detectChanges(); // re-render after the state change
expect(fixture.nativeElement.textContent).toContain('Count: 1');
});
});
/*
Notes:
- Standalone components are listed in imports (not declarations).
- detectChanges() is called twice: once after createComponent to
render the initial view, and again after the button click to
reflect the updated count. Skipping either leaves the asserted DOM
stale — the classic Angular-testing gotcha.
*/