Component testing helps you check if parts of your app work right by themselves. It finds mistakes early and keeps your app strong.
Component testing basics in Angular
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MyComponent } from './my.component'; describe('MyComponent', () => { let component: MyComponent; let fixture: ComponentFixture<MyComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [MyComponent] }).compileComponents(); fixture = TestBed.createComponent(MyComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
Use TestBed to set up the testing environment for your component.
fixture.detectChanges() runs Angular's change detection to update the view.
title property equals 'Hello'.it('should have title as Hello', () => { expect(component.title).toBe('Hello'); });
<h1> tag.it('should render title in h1 tag', () => { const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('h1')?.textContent).toContain('Hello'); });
This example shows a simple Angular component with a greeting message. The test checks if the component is created, if the greeting property has the right text, and if the text appears in the HTML inside an <h1> tag.
import { Component } from '@angular/core'; @Component({ selector: 'app-greeting', template: `<h1>{{ greeting }}</h1>` }) export class GreetingComponent { greeting = 'Hello, Angular!'; } // Test file: greeting.component.spec.ts import { ComponentFixture, TestBed } from '@angular/core/testing'; import { GreetingComponent } from './greeting.component'; describe('GreetingComponent', () => { let component: GreetingComponent; let fixture: ComponentFixture<GreetingComponent>; beforeEach(() => { TestBed.configureTestingModule({ declarations: [GreetingComponent] }).compileComponents(); fixture = TestBed.createComponent(GreetingComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create the component', () => { expect(component).toBeTruthy(); }); it('should have greeting text', () => { expect(component.greeting).toBe('Hello, Angular!'); }); it('should render greeting in h1 tag', () => { const compiled = fixture.nativeElement as HTMLElement; expect(compiled.querySelector('h1')?.textContent).toContain('Hello, Angular!'); }); });
Always import ComponentFixture and TestBed from @angular/core/testing.
Use fixture.nativeElement to access the rendered HTML for checking content.
Run fixture.detectChanges() after changing component properties to update the view.
Component testing checks if parts of your app work alone.
Use TestBed to set up and create components for testing.
Check both component properties and rendered HTML to ensure correct behavior.