Angular › Testing with Jasmine & Karma
How do you use Angular's TestBed to test a component that depends on a service?
IntermediateAnswer
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.