Sub topic 4
Creating components with TestBed
This chapter assumes you know basic TypeScript, Angular standalone components and dependency injection, and signals with input() and output(). It also assumes you can run ng test as set up in the previous chapters.
What TestBed does
TestBed is Angular's testing utility. It builds a small, isolated Angular environment with its own injector, and it can create real component instances inside that environment. You test a component by letting Angular construct it, the way it would at runtime, instead of calling new CounterComponent() yourself. This matters because inject(), templates, and signal inputs only work inside Angular's injection context.
Creating a component
The component under test is the CounterComponent from the topic plan. Because it is standalone, it needs no declarations array and no imports entry. You can pass it straight to createComponent.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent creation', () => {
it('creates the component', () => {
const fixture = TestBed.createComponent(CounterComponent);
expect(fixture.componentInstance).toBeInstanceOf(CounterComponent);
});
});createComponent returns a ComponentFixture. It is a wrapper around the component with three members you will use constantly:
| Member | What it gives you |
|---|---|
| `componentInstance` | The component class instance, for calling methods and reading public members |
| `nativeElement` | The host DOM element, for querying rendered output |
| `componentRef` | The Angular `ComponentRef`, used for `setInput` |
The component exists after this call, but its template has not been rendered yet. The next chapter covers detectChanges.
Configuring the test environment
Call TestBed.configureTestingModule before createComponent when the component needs providers or extra imports. It accepts the same providers and imports as an NgModule.
import { TestBed } from '@angular/core/testing';
import { InjectionToken, inject, Component } from '@angular/core';
import { describe, it, expect } from 'vitest';
const GREETING = new InjectionToken<string>('GREETING');
@Component({
selector: 'app-greeter',
template: `<p>{{ greeting }}</p>`,
})
class GreeterComponent {
protected readonly greeting = inject(GREETING);
}
describe('GreeterComponent', () => {
it('uses the provider configured for the test', () => {
TestBed.configureTestingModule({
providers: [{ provide: GREETING, useValue: 'Hello, test' }],
});
const fixture = TestBed.createComponent(GreeterComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Hello, test');
});
});To get a service from the same injector the component uses, call TestBed.inject(Token).
Isolation between tests
Angular resets the TestBed after every test. Each it starts with a fresh injector, so providers and component instances do not leak from one test to the next. You do not need to write cleanup code for TestBed itself. Fake timers and vi spies are a different matter, because Vitest manages them and you restore them yourself.
Common errors
NullInjectorError: No provider for ...: the component or one of its dependencies injects something that the test injector cannot supply. Add the provider inconfigureTestingModule. ForHttpClient, addprovideHttpClient().- Configuring after creating: calling
configureTestingModuleaftercreateComponentin the same test throws an error, because the injector is already instantiated. Always configure first, usually inbeforeEachor at the top of the test. - Empty DOM: if
nativeElementhas no content, you probably have not calledfixture.detectChanges()yet. - Setting a signal input directly:
fixture.componentInstance.step = ...does not work, because inputs created withinput()are read-only. Usefixture.componentRef.setInput('step', 5).
Exercise
A test calls TestBed.createComponent(UserListComponent) and fails with NullInjectorError: No provider for HttpClient. What do you change, and where must the change happen?
Show answer
Add provideHttpClient() to the providers array in TestBed.configureTestingModule, and call that before createComponent. Once the component has been created, the injector can no longer be reconfigured. A better fix for a component test is to provide a mock UserService, so no HTTP client is needed.