Sub topic 4
Creating components with TestBed
This chapter covers how TestBed builds a component for a test. It assumes you can write a basic Vitest test with describe, it, and expect, and that you know standalone components, inject(), and signal inputs. You also need to be able to run ng test.
What TestBed does
A component can't be created with new CounterComponent() in a useful way. Its template needs a compiler, its dependencies need an injector, and its inputs and outputs need Angular's wiring. TestBed provides all of these. It builds a small Angular environment for each test: a root injector, a renderer, and a DOM host element. It then lets you create real components inside it.
The flow has three parts:
- Optionally configure the environment with
TestBed.configureTestingModule. - Create a component with
TestBed.createComponent, which returns aComponentFixture. - Interact with the fixture and assert on what you see.
The smallest useful test
Standalone components declare their own template dependencies, so TestBed can create them without any configuration. This test uses the CounterComponent from the plan: it has a step input, a changed output, and a private count signal.
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);
});
it('does not render the template until change detection runs', () => {
const fixture = TestBed.createComponent(CounterComponent);
expect(fixture.nativeElement.textContent).toBe('');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Count: 0');
});
});The second test shows a behavior that surprises many people. createComponent instantiates the class, but it doesn't render bindings. The first fixture.detectChanges() call renders the template. Lifecycle hooks such as ngOnInit also run on that first call. The next chapter covers change detection in detail.
What the fixture gives you
createComponent returns a ComponentFixture<T>. These are the members you use most.
| Member | What it is | Typical use |
|---|---|---|
| `componentInstance` | The component class instance | Call methods, subscribe to outputs |
| `componentRef` | The `ComponentRef` | `setInput('step', 5)` to set inputs |
| `nativeElement` | The host DOM element | `querySelector` and text checks |
| `debugElement` | Angular's wrapper around the host | Query by directive, read injectors |
| `detectChanges()` | Runs change detection once | Render after a state change |
| `whenStable()` | Promise that resolves when async work settles | Wait for pending tasks |
Prefer componentRef.setInput() over assigning to componentInstance.step. Signal inputs are read-only from outside, so assignment doesn't compile. setInput also goes through Angular's normal input path.
Configuring the testing module
Use configureTestingModule when the component needs something the default environment doesn't provide. This usually means providers, such as an HTTP client, a router, or a replacement service. Here is a component with a dependency:
import { Component, inject, Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeService {
readonly name = signal('light');
}
@Component({
selector: 'app-badge',
template: `<span data-testid="theme">{{ theme.name() }}</span>`,
})
export class BadgeComponent {
protected readonly theme = inject(ThemeService);
}The test replaces ThemeService with a plain object:
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { BadgeComponent, ThemeService } from './badge.component';
describe('BadgeComponent', () => {
it('shows the theme name from the service', () => {
TestBed.configureTestingModule({
providers: [{ provide: ThemeService, useValue: { name: signal('dark') } }],
});
const fixture = TestBed.createComponent(BadgeComponent);
fixture.detectChanges();
const text = fixture.nativeElement.querySelector('[data-testid="theme"]').textContent;
expect(text).toBe('dark');
});
});The imports array in configureTestingModule also accepts standalone components. Older tests list the component under test there (imports: [BadgeComponent]). That is harmless but not required. imports is still useful for providers packaged as modules or for helper standalone directives that the test needs.
Order matters
configureTestingModule must run before the first createComponent or TestBed.inject in the same test. After either call, TestBed has built the module. A later configuration call throws an error saying the test module has already been instantiated.
Getting services from the environment
TestBed.inject(Token) returns the instance from the root injector of the testing module. The component receives the same instance, so you can arrange state before rendering and inspect it afterward.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { BadgeComponent, ThemeService } from './badge.component';
describe('BadgeComponent with the real service', () => {
it('re-renders when the shared service changes', () => {
const theme = TestBed.inject(ThemeService);
const fixture = TestBed.createComponent(BadgeComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('light');
theme.name.set('dark');
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('dark');
});
});This test uses the real ThemeService, so providedIn: 'root' works without any configuration. The component and the test share one instance.
Isolation between tests
The Angular test setup resets TestBed between tests. Each test gets a new injector, new service instances, and new fixtures. Fixtures from the earlier test are destroyed, and their DOM is removed. As a result:
- A service's state doesn't leak from one test to the next.
- You must repeat
configureTestingModulein each test, or put it inbeforeEach. - Module-level variables are not reset. If your test file keeps its own
letstate, you reset it yourself.
import { TestBed } from '@angular/core/testing';
import { beforeEach, describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent isolation', () => {
let fixture: ReturnType<typeof createFixture>;
function createFixture() {
return TestBed.createComponent(CounterComponent);
}
beforeEach(() => {
fixture = createFixture();
fixture.detectChanges();
});
it('starts at zero', () => {
expect(fixture.nativeElement.textContent).toContain('Count: 0');
});
it('starts at zero again after another test clicked the button', () => {
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Count: 1');
});
});A setup helper for many tests
Repeating the create, set input, and detect sequence in every test is noisy. A small function at the top of the file keeps tests short and lets each test state only what is different.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
function setup(step = 1) {
const fixture = TestBed.createComponent(CounterComponent);
fixture.componentRef.setInput('step', step);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
return { fixture, element };
}
describe('CounterComponent setup helper', () => {
it('uses the default step', () => {
const { element } = setup();
element.querySelector('button')!.click();
expect(element.textContent).toContain('Count: 0');
});
it('uses a custom step', () => {
const { fixture, element } = setup(10);
element.querySelector('button')!.click();
fixture.detectChanges();
expect(element.textContent).toContain('Count: 10');
});
});The first test is deliberate. It clicks without calling detectChanges, so the old text remains. This shows that the DOM updates only when you run change detection.
Overriding what a component uses
Sometimes you want to change something declared on the component itself. TestBed.overrideComponent replaces parts of the component's metadata. It must run before createComponent.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
@Component({
selector: 'app-panel',
template: `<h2>Panel</h2><ng-content />`,
})
class PanelComponent {}
describe('overrideComponent', () => {
it('can swap the template', () => {
TestBed.overrideComponent(PanelComponent, {
set: { template: '<h2>Stub panel</h2>' },
});
const fixture = TestBed.createComponent(PanelComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Stub panel');
});
});Use overrides sparingly. A test that replaces the template no longer tests the template. Component-level providers are the more common reason to override, because they take precedence over the testing module's providers. If a component lists providers: [ThemeService] itself, a provider in configureTestingModule won't affect it. Use overrideComponent with set: { providers: [...] } for that case.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for HttpClient` | The component or a service needs `HttpClient` | Add `provideHttpClient()` and `provideHttpClientTesting()` to `providers` |
| Error that the test module is already instantiated | `configureTestingModule` ran after `inject` or `createComponent` | Move configuration to the start of the test or into `beforeEach` |
| Template text is empty or stale | No `detectChanges()` after creation or a state change | Call `fixture.detectChanges()` |
| Provider override has no effect | The component declares its own `providers` | Use `overrideComponent` |
| Test passes alone but fails in the suite | State kept outside `TestBed`, such as module variables | Reset that state in `beforeEach` |
Exercise
A test calls TestBed.inject(ThemeService) on its first line, then calls TestBed.configureTestingModule({ providers: [...] }) to replace ThemeService, then creates BadgeComponent. What goes wrong, and how do you fix it?
Show answer
The inject call instantiates the testing module, so the later configureTestingModule call throws an error saying the module has already been instantiated. Move configureTestingModule before the first inject or createComponent. Then call TestBed.inject(ThemeService) to get the replacement instance.
Exercise
You create a CounterComponent with TestBed.createComponent and immediately read fixture.nativeElement.textContent. Why is it empty, and what single call renders it?
Show answer
createComponent builds the instance but does not run change detection, so the template bindings have not rendered. Calling fixture.detectChanges() renders the template and runs ngOnInit.