Sub topic 14
Testing with TestBed and Test Doubles
This chapter assumes you know the provider recipes from earlier chapters (useClass, useValue, useFactory) and can read a basic Jasmine or Jest spec with describe, it, and expect. Dependency injection makes testing easier. A component asks for a CartService without creating one, so a test can hand it a different object, called a test double, and the component won't notice.
What TestBed Does
TestBed is Angular's testing utility. It builds a test environment injector for each spec. You pass providers to TestBed.configureTestingModule(), and they follow the same rules as providers passed to bootstrapApplication(). If a provider you register uses the same token as a real service, your provider wins inside that test.
Testing a Service Directly
A root service with no dependencies needs no setup. Ask the test injector for it with TestBed.inject():
import { TestBed } from '@angular/core/testing';
import { CartService } from './cart.service';
describe('CartService', () => {
let cart: CartService;
beforeEach(() => {
TestBed.configureTestingModule({});
cart = TestBed.inject(CartService);
});
it('counts added items', () => {
cart.add('apple');
cart.add('pear');
expect(cart.count()).toBe(2);
});
});TestBed resets between specs, so each it gets a new CartService and state does not leak between tests.
Replacing a Dependency in a Component Test
To test CartBadgeComponent without the real cart, provide a plain object under the CartService token:
import { TestBed } from '@angular/core/testing';
import { CartService } from './cart.service';
import { CartBadgeComponent } from './cart-badge.component';
import { signal } from '@angular/core';
describe('CartBadgeComponent', () => {
it('shows the count from CartService', () => {
const fakeCart = { count: signal(3) };
TestBed.configureTestingModule({
imports: [CartBadgeComponent],
providers: [{ provide: CartService, useValue: fakeCart }]
});
const fixture = TestBed.createComponent(CartBadgeComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Items: 3');
});
});The fake only needs the members the component actually uses, which here is count. Standalone components go in imports, not declarations.
Choosing a Recipe for the Double
| Recipe | Use it when |
|---|---|
| `useValue` | A small object literal or spy object is enough |
| `useClass` | The fake has its own logic or needs its own dependencies |
| `useFactory` | The double depends on other injected values or test setup |
Common Errors
- Overriding after creation. Call
configureTestingModule()before the firstTestBed.inject()orcreateComponent(). Once the injector exists, later configuration throws an error. - Component-level providers ignore your override. If a component lists a service in its own
providersarray, asEditorComponentdoes withFormDraftService, its element injector answers first. A provider inconfigureTestingModulenever gets asked. Override the component itself:
TestBed.overrideComponent(EditorComponent, {
set: { providers: [{ provide: FormDraftService, useValue: { value: 'draft' } }] }
});- Type mismatch on the fake. A
useValueobject is not type-checked againstCartService. If the component starts using a new method, the test fails at runtime and the compiler won't warn you. Typing the fake asPartial<CartService>documents what it covers.
Exercise
A spec provides { provide: FormDraftService, useValue: fake } in configureTestingModule, but EditorComponent still uses a real FormDraftService. Why, and how do you fix it?
Show answer
EditorComponent lists FormDraftService in its own providers, so its element injector resolves the token before the test environment injector is consulted. Use TestBed.overrideComponent(EditorComponent, { set: { providers: [{ provide: FormDraftService, useValue: fake }] } }) to replace the component-level provider.
Exercise
Why does calling TestBed.inject(CartService) in two separate it blocks give two different instances, even though CartService is providedIn: 'root'?
Show answer
TestBed builds a fresh test environment injector for each spec and tears it down afterward. "Root" in a test means that spec's root injector, so each spec gets its own instance.