Back to results for “Services & Dependency Injection”
Angular › Testing with Jasmine & Karma

How do you use Angular's TestBed to test a component that depends on a service?

Intermediate

Answer

TestBed lets you configure a testing module specifically for your test, providing either the real service or a mock version, then create an instance of your component within that controlled testing environment to verify its behavior.
TestBed.configureTestingModule({
  imports: [UserListComponent],
  providers: [{ provide: UserService, useValue: { getUsers: () => of([{ name: 'Alice' }]) } }]
});

const fixture = TestBed.createComponent(UserListComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Alice');
Real-world example A test for a user list component provides a fake UserService returning predictable sample data, verifying the component correctly displays that data without needing a real backend server running during the test.

Common follow-ups: Why do you need to call fixture.detectChanges() before checking the rendered output?;What is the difference between TestBed.createComponent and directly instantiating a component class?