Sub topic 3
Creating and Injecting Services with TestBed
This chapter assumes you know TypeScript, Angular services and dependency injection, and how to run unit tests with the Angular CLI. You should also be comfortable reading RxJS Observables. The earlier chapter showed that a service with no dependencies can be created with new. Here you will learn when to switch to TestBed, how it builds an injector for each test, and the errors that appear when the setup is wrong.
Why TestBed exists
A plain new CartService() works only while the class needs nothing from Angular. Most services do. They call inject(HttpClient), read an injection token, or depend on another service. If you call new UserService() for a service that uses inject() in a field initializer, Angular throws an error, because no injection context exists outside a framework-managed construction.
TestBed is Angular's testing utility that builds a small, throwaway module and injector for one test. You list the providers that test needs, and TestBed.inject() returns instances created the same way the running application would create them.
Use TestBed when any of these is true:
- The service uses
inject()or constructor injection. - You want to replace a dependency with a stub.
- You need the real
HttpClientwiring, with only the backend replaced. - You want to test the service as the application sees it, including its
providedInscope.
Keep using new for dependency-free classes. Those tests are faster and have less setup to maintain.
The basic shape
The smallest TestBed test configures nothing and injects a service that is providedIn: 'root'.
import { Injectable } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
export class CounterService {
private count = 0;
increment(): number {
return ++this.count;
}
}
describe('CounterService', () => {
let service: CounterService;
beforeEach(() => {
service = TestBed.inject(CounterService);
});
it('counts upward from one', () => {
expect(service.increment()).toBe(1);
expect(service.increment()).toBe(2);
});
it('starts from zero in every test', () => {
expect(service.increment()).toBe(1);
});
});The second test passes even though the first one already incremented a counter. The reason is that Angular resets the testing module between tests, so each TestBed.inject() call in a new test creates a fresh instance. You can rely on this isolation and do not need to reset state by hand.
Configuring providers
When a service is not providedIn: 'root', or when you need to change what is provided, call TestBed.configureTestingModule() with a providers array. The following service is registered only through the test configuration.
import { Injectable, InjectionToken, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
export const API_BASE = new InjectionToken<string>('API_BASE');
@Injectable()
export class UrlBuilder {
private readonly base = inject(API_BASE);
userUrl(id: number): string {
return `${this.base}/users/${id}`;
}
}
describe('UrlBuilder', () => {
it('prefixes paths with the configured base URL', () => {
TestBed.configureTestingModule({
providers: [
UrlBuilder,
{ provide: API_BASE, useValue: 'https://example.test' },
],
});
const builder = TestBed.inject(UrlBuilder);
expect(builder.userUrl(3)).toBe('https://example.test/users/3');
});
});Two things matter here. First, UrlBuilder has a bare @Injectable(), so nothing registers it automatically and it must appear in providers. Second, API_BASE is a token with no default value, so omitting it from the test configuration would fail at injection time.
What happens inside TestBed
The flow below shows the order of events in a typical test. Configuration must come first, because the first call to TestBed.inject() locks the module.
The consequence is a rule you will hit sooner or later: call configureTestingModule() before the first inject() in a test. If you call it afterward, Angular raises an error saying the test module has already been instantiated.
Choosing where to configure and inject
You have three common places to put setup, and each has a purpose.
| Location | Use it for | Watch out for |
|---|---|---|
| `beforeEach` | Providers and injection shared by every test in the block | A provider that only one test needs leaks into the others |
| Inside the `it` | Configuration unique to that test | Repeated setup if many tests do the same thing |
| A helper function | Setup with options, such as a stub that returns different values | Hiding what the test depends on if the helper does too much |
A helper function is useful when several tests differ in one detail. It keeps each test short while making the difference visible.
import { Injectable, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
export class FeatureFlags {
isEnabled(name: string): boolean {
return false;
}
}
@Injectable({ providedIn: 'root' })
export class Greeter {
private readonly flags = inject(FeatureFlags);
greet(name: string): string {
return this.flags.isEnabled('formal') ? `Good day, ${name}.` : `Hi ${name}!`;
}
}
function setup(formal: boolean): Greeter {
TestBed.configureTestingModule({
providers: [{ provide: FeatureFlags, useValue: { isEnabled: () => formal } }],
});
return TestBed.inject(Greeter);
}
describe('Greeter', () => {
it('uses a casual greeting by default', () => {
expect(setup(false).greet('Ada')).toBe('Hi Ada!');
});
it('uses a formal greeting when the flag is on', () => {
expect(setup(true).greet('Ada')).toBe('Good day, Ada.');
});
});Each call to setup() runs in a different test, so each gets a clean module. Calling setup() twice inside one test would fail for the reason described above.
inject() versus the injector
TestBed.inject() is the standard way to get an instance. You may see older code that uses TestBed.get(), which was removed from current Angular versions. Prefer inject(), which is also typed. The return type follows the token you pass, so TestBed.inject(CounterService) gives you a CounterService with no cast.
To run code that itself calls the inject() function, such as a helper that reads a dependency, use TestBed.runInInjectionContext().
import { inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
function readBase(): string {
return inject(API_BASE);
}
it('runs a function that calls inject()', () => {
TestBed.configureTestingModule({
providers: [{ provide: API_BASE, useValue: 'https://example.test' }],
});
const base = TestBed.runInInjectionContext(readBase);
expect(base).toBe('https://example.test');
});This reuses the API_BASE token from the earlier example. It is the same mechanism the framework uses when it creates a service, so the function sees exactly the dependencies you configured.
Scope and instance sharing
An injector hands out one instance of a provider per injector. In a test, that means every call to TestBed.inject(CounterService) within the same test returns the same object.
it('returns the same instance within a test', () => {
const first = TestBed.inject(CounterService);
const second = TestBed.inject(CounterService);
expect(first).toBe(second);
});This matters when a service holds state. Two classes that both inject CounterService share one counter during a test. It also explains why a stub supplied with useValue is the very object you pass in, so a spy you keep a reference to will record calls made by the service under test.
Common errors
Most setup failures produce a recognizable message. Matching the message to its cause saves time.
NullInjectorError: No provider for X. The service or token is not provided in the test module, and it has noprovidedIn: 'root'. Add it toproviders.inject() must be called from an injection context. You callednewon a class that usesinject()in a field initializer. Create it withTestBed.inject()instead.- An error that the test module is already instantiated. You called
configureTestingModule()afterinject()in the same test. Move configuration earlier. - A test passes alone and fails in a group. A provider is configured in a shared
beforeEach, and another test expected a different one. Configure per test or use a helper.
Summary of the working model
TestBedbuilds one injector per test from the providers you list, plus anyprovidedIn: 'root'services.- Configure first, then inject. The first
inject()locks the module. - Each test starts clean, so state does not carry between tests.
- Within a test, an injector returns one instance per provider.
- Use
newfor dependency-free services andTestBedfor everything that touches injection.
The next chapters build on this. Replacing dependencies with stubs uses the providers array you saw here, and setting up HttpClient for testing is another provider list passed to the same configureTestingModule() call.
Exercise
A service ReportService has private readonly clock = inject(Clock); as a field, and Clock is a class with providedIn: 'root'. You want a test where Clock.now() always returns 1000. Write the TestBed setup and the line that obtains the service. Then say what error you would get if you wrote new ReportService() instead.
Show answer
Configure the stub before injecting: TestBed.configureTestingModule({ providers: [{ provide: Clock, useValue: { now: () => 1000 } }] }); const service = TestBed.inject(ReportService);. If you wrote new ReportService(), Angular would throw an error that inject() must be called from an injection context, because the field initializer runs outside any injector.
Exercise
A test calls TestBed.inject(CounterService), increments it, and then calls TestBed.configureTestingModule({ providers: [...] }) to add a provider. What goes wrong, and how do you fix it?
Show answer
Angular reports that the test module is already instantiated, because the first inject() locked the configuration. Move configureTestingModule() before the first inject() call, or split the scenario into two tests.