Unit Testing a Component (TestBed + Mock Service)
Write a clean unit test for a component by mocking its service dependency.
Let’s test a component that loads a username from a service. ## Component ```ts import { Component } from '@angular/core'; import { UserService } from './user.service'; @Component({ selector: 'app-greeting', standalone: true, template: `<h1>Hello {{ name }}</h1>`, }) export class GreetingComponent { name = ''; constructor(userService: UserService) { this.name = userService.getName(); } } ``` ## Test idea We do not want to use the real service in a unit test. We mock it. ```ts import { TestBed } from '@angular/core/testing'; import { GreetingComponent } from './greeting.component'; import { UserService } from './user.service'; describe('GreetingComponent', () => { it('shows name from service', () => { TestBed.configureTestingModule({ imports: [GreetingComponent], providers: [ { provide: UserService, useValue: { getName: () => 'Jessica Miller' }, }, ], }); const fixture = TestBed.createComponent(GreetingComponent); fixture.detectChanges(); const el: HTMLElement = fixture.nativeElement; expect(el.textContent).toContain('Hello Jessica Miller'); }); }); ``` ## Why this is clean - component is tested in isolation - predictable output - fast execution > Next: HTTP testing with HttpTestingController.