Sub topic 3
Creating and injecting services with TestBed
This chapter assumes you know TypeScript, Angular services and dependency injection, and how to run ng test. It covers how to get a service instance from TestBed and what that instance shares with other tests.
Why use TestBed
The previous chapter created a service with new. That works only when the constructor needs no arguments and the class does not call inject(). Most real services depend on other services. TestBed builds a small Angular injector for each test, so those dependencies are resolved the way they are in the app.
Injecting a root-provided service
A service declared with providedIn: 'root' needs no provider in the test. Call configureTestingModule and then TestBed.inject.
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(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CounterService);
});
it('counts from one', () => {
expect(service.increment()).toBe(1);
expect(service.increment()).toBe(2);
});
it('starts fresh in every test', () => {
expect(service.increment()).toBe(1);
});
});The second test passes even though the first one already incremented the counter. TestBed resets its injector after each test, so every it gets a new instance.
Providing a service that is not in root
A service with a plain @Injectable() decorator has no default provider. Inject it without registering it and Angular throws a NullInjectorError. Add it to providers.
import { Injectable } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Injectable()
export class FeatureFlags {
isOn(name: string): boolean {
return name === 'beta';
}
}
describe('FeatureFlags', () => {
it('is available once it is listed in providers', () => {
TestBed.configureTestingModule({ providers: [FeatureFlags] });
const flags = TestBed.inject(FeatureFlags);
expect(flags.isOn('beta')).toBe(true);
});
});How the pieces fit
The order matters. Call configureTestingModule before the first TestBed.inject in a test. After inject has run, the injector is created and later configuration calls fail with an error.
One instance per injector
Inside a single test, every inject call for the same token returns the same object, because services are singletons within their injector.
it('returns the same instance within one test', () => {
TestBed.configureTestingModule({});
const a = TestBed.inject(CounterService);
const b = TestBed.inject(CounterService);
expect(a).toBe(b);
});Use this when a service under test and a helper both depend on a shared service. Both receive the same object.
Services that call inject()
Many services read their dependencies with inject() in a field initializer. That call only works inside an injection context, so new MyService() in a test throws. Get the instance from TestBed instead. To run a function in the test injector's context, use TestBed.runInInjectionContext:
const value = TestBed.runInInjectionContext(() => new CounterService().increment());
expect(value).toBe(1);Common errors
NullInjectorError: No provider for X. The service is notprovidedIn: 'root'and is missing fromproviders.- Sharing one instance across tests by creating it outside
beforeEach. State then leaks between tests. Create it insidebeforeEachor inside eachit. - Calling
configureTestingModuleafterTestBed.inject. Configure first. - Using
newon a service that callsinject(). UseTestBed.inject.
Exercise
A service is declared with a bare @Injectable() and no providedIn. Your test calls TestBed.configureTestingModule({}) and then TestBed.inject(MyService). What happens, and how do you fix it?
Show answer
Angular throws NullInjectorError: No provider for MyService, because nothing registers the service in the test injector. Fix it by passing the class in the providers array: TestBed.configureTestingModule({ providers: [MyService] }).