How to test Angular components
Testing Angular components is essential for maintaining code quality and preventing regressions as your application grows and evolves. With over 12 years of Angular development experience since 2014 and as the creator of CoreUI, I’ve written thousands of component tests for production applications. Angular CLI automatically generates test files using TestBed for component creation and Jasmine for assertions. The testing approach involves creating a component instance, detecting changes, and asserting that the component renders and behaves correctly.
Use TestBed to create component instances and Jasmine to assert component behavior and rendering.
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { UserCardComponent } from './user-card.component'
describe('UserCardComponent', () => {
let component: UserCardComponent
let fixture: ComponentFixture<UserCardComponent>
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [UserCardComponent]
}).compileComponents()
fixture = TestBed.createComponent(UserCardComponent)
component = fixture.componentInstance
fixture.detectChanges()
})
it('should create', () => {
expect(component).toBeTruthy()
})
it('should display user name', () => {
component.userName = 'John Doe'
fixture.detectChanges()
const compiled = fixture.nativeElement
expect(compiled.querySelector('h2').textContent).toContain('John Doe')
})
it('should emit event on button click', () => {
spyOn(component.userSelected, 'emit')
const button = fixture.nativeElement.querySelector('button')
button.click()
expect(component.userSelected.emit).toHaveBeenCalled()
})
})
Best Practice Note
Call fixture.detectChanges() after modifying component properties to trigger Angular’s change detection and update the DOM. Use DebugElement for more robust queries that work across platforms. For testing components with dependencies, provide mock services in the TestBed configuration. Run tests with ng test which launches Karma test runner. This is the same testing pattern we use in CoreUI for Angular to ensure every component works reliably across different Angular versions and configurations.



