Component Testing in Angular

From the Angular cheat sheet · Testing · verified Jul 2026

Component Testing

Testing Angular components with TestBed

typescript
// Basic component test
import { ComponentFixture, TestBed } from '@angular/core/testing';

describe('UserComponent', () => {
  let component: UserComponent;
  let fixture: ComponentFixture<UserComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [ UserComponent ]   // standalone components go in imports, not declarations
    }).compileComponents();

    fixture = TestBed.createComponent(UserComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should render title', () => {
    const compiled = fixture.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('User Profile');
  });
});
💡 Use TestBed.configureTestingModule to set up test environment
⚡ Mock external dependencies for isolated unit tests
📌 Use fixture.detectChanges() to trigger change detection
🔥 HttpTestingController helps test HTTP requests without actual calls
Back to the full Angular cheat sheet