Sub topic 14
Overriding providers in tests
This chapter shows how to replace scoped providers in unit tests. It assumes you know the following:
- Standalone components and
inject(). - The
providersarray on@Component. - The basic
TestBedworkflow of configuring, creating a fixture and callingdetectChanges(). - The resolution order covered earlier: element injectors first, then environment injectors.
Why scoped providers need different handling
In a test, TestBed builds a test environment injector. Values you pass to TestBed.configureTestingModule({ providers: [...] }) land there, next to the root providers.
Angular resolves a dependency by checking the element injector chain first. Only after that does it fall back to the environment injector. If a component lists a service in its own providers, the element injector for that component answers the request. The environment injector is never consulted, so a replacement registered there is ignored.
This explains a common failure. A developer registers a fake with configureTestingModule, the test still runs the real service, and the real service's side effects (HTTP calls, timers) appear in the output.
The three layers and where to override each
| Where the real provider lives | How to replace it in a test |
|---|---|
| `providedIn: 'root'` or app config | `providers` in `configureTestingModule` |
| Component or directive `providers` | `TestBed.overrideComponent` (or `overrideDirective`) |
| Route `providers` | Build a test route table with the fake, or provide the fake in the test's route config |
Replacing a root service
A service with providedIn: 'root' is the simplest case. Register a replacement for the same token in the testing module. The test environment injector then holds your fake, and nothing closer to the component shadows it.
import { TestBed } from '@angular/core/testing';
import { CounterService } from './counter.service';
class FakeCounterService {
readonly count = () => 7;
increment(): void {}
}
it('uses the fake root service', () => {
TestBed.configureTestingModule({
providers: [{ provide: CounterService, useClass: FakeCounterService }],
});
const service = TestBed.inject(CounterService);
expect(service.count()).toBe(7);
});TestBed.inject reads from the test environment injector. It is the right tool for root services, but it cannot see a component's own providers (see the pitfalls below).
Replacing a component-level provider
When the component declares providers: [CounterService], use overrideComponent. It edits the component's metadata before the component is compiled, so the element injector is built with your fake from the start.
import { TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
import { CounterService } from './counter.service';
class FakeCounterService {
readonly count = () => 42;
increment(): void {}
}
it('renders the count from a component-scoped service', () => {
TestBed.configureTestingModule({ imports: [CounterComponent] });
TestBed.overrideComponent(CounterComponent, {
set: { providers: [{ provide: CounterService, useClass: FakeCounterService }] },
});
const fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('42');
});Two rules apply here:
- Call
overrideComponentbeforeTestBed.createComponent. After the first component is created, the testing module is locked and further overrides throw an error. setreplaces the wholeprovidersarray. If the component lists several providers, include every one the test still needs, or useremoveandaddto change only some entries.
set, add and remove
overrideComponent takes an object with set, add or remove. Each one changes the metadata in a different way.
| Key | Effect on the metadata field |
|---|---|
| `set` | Replaces the field with the value you give |
| `add` | Appends to the existing field |
| `remove` | Deletes matching entries from the existing field |
Use remove and add together when you want to swap a single provider and leave the rest alone:
TestBed.overrideComponent(CounterComponent, {
remove: { providers: [CounterService] },
add: { providers: [{ provide: CounterService, useClass: FakeCounterService }] },
});remove matches the entry by identity. It removes CounterService because the component listed the class itself. It will not remove an entry written as an object, such as { provide: CounterService, useClass: Real }, unless you pass that same object reference.
Reaching the instance a component actually uses
Sometimes you do not want a fake. You want to inspect or drive the real, component-scoped instance. TestBed.inject(CounterService) fails here. It asks the environment injector, which has no CounterService (or has a different, root-level one).
Ask the component's own injector through the fixture instead:
import { TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
import { CounterService } from './counter.service';
it('gives each component instance its own service', () => {
TestBed.configureTestingModule({ imports: [CounterComponent] });
const first = TestBed.createComponent(CounterComponent);
const second = TestBed.createComponent(CounterComponent);
first.detectChanges();
second.detectChanges();
const firstService = first.debugElement.injector.get(CounterService);
const secondService = second.debugElement.injector.get(CounterService);
firstService.increment();
expect(firstService.count()).toBe(1);
expect(secondService.count()).toBe(0);
expect(firstService).not.toBe(secondService);
});This test checks the scoping itself. It fails if someone removes providers: [CounterService] from the component, because both fixtures would then share the root instance. A test like this protects a design decision that is otherwise invisible.
Route-level providers
Providers on a route live in an environment injector that the router creates when the route is first activated. TestBed does not create that injector, so overrideComponent and configureTestingModule cannot reach it.
You have two practical options:
- Test the routed component on its own. Route
providersare not involved, so provide the fake throughconfigureTestingModuleoroverrideComponentas needed. - To test the navigation itself, pass your own route table to
provideRouterand list the fake in that route'sproviders. The router then builds its environment injector with the fake.
import { Routes } from '@angular/router';
import { AdminComponent } from './admin.component';
import { AdminSettingsService } from './admin-settings.service';
class FakeAdminSettingsService {
readonly theme = 'test';
}
export const testRoutes: Routes = [
{
path: 'admin',
component: AdminComponent,
providers: [{ provide: AdminSettingsService, useClass: FakeAdminSettingsService }],
},
];Provide this table with provideRouter(testRoutes) in the testing module's providers.
Common pitfalls
- Fake registered in the wrong layer. The test passes a fake through
configureTestingModule, but the component has its ownprovidersentry. The real service wins. UseoverrideComponent. - Override called too late. Calling
overrideComponentaftercreateComponentthrows an error, because the testing module has already been instantiated. - Reading the wrong instance.
TestBed.injectreturns the environment-level instance. A component-scoped instance is only visible throughfixture.debugElement.injector. - State leaking between tests.
TestBedresets its configuration between tests, so fakes do not carry over. A fake kept in a module-level variable does. Create a new fake in each test or inbeforeEach. - Missing token in the fake's injector. If the component under test injects a second service that is only provided by a parent component, the isolated test throws
NullInjectorError. Provide a fake for it, or mark the injectionoptionalin the component if it is genuinely optional.
A short checklist
- Find where the real provider is declared: root, route or component.
- Register the fake in the matching layer, using the table above.
- Do any overriding before the first
createComponent. - Read component-scoped instances from
fixture.debugElement.injector. - Add one test that asserts the scoping itself, such as two fixtures getting different instances.
Exercise
A component declares providers: [SearchService]. A test registers { provide: SearchService, useClass: FakeSearchService } in configureTestingModule, yet the component still calls the real service. Why, and how do you fix it?
Show answer
The component's element injector holds its own SearchService entry, and Angular checks element injectors before the environment injector that TestBed configures, so the fake is never reached. Fix it by calling TestBed.overrideComponent(TheComponent, { set: { providers: [{ provide: SearchService, useClass: FakeSearchService }] } }) before TestBed.createComponent.
Exercise
You want to assert that two instances of CounterComponent do not share state. Which injector do you use to read each instance's CounterService, and why is TestBed.inject(CounterService) the wrong choice?
Show answer
Use fixture.debugElement.injector.get(CounterService) for each fixture. TestBed.inject queries the test environment injector, which does not hold the component-scoped instances (and would return a root instance or throw if none exists), so it cannot show per-component state.