Angular Academy · Lesson

TestBed and Component Fixtures

Configure and create components in tests.

Lesson 1 of 413 steps

TestBed and Component Fixtures is a free Angular Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, and your progress syncs across the web and the CoddyKit app. The Angular Academy course includes 4 lessons in total.

Why TestBed Exists

Angular components depend on the framework: dependency injection, change detection, and the template compiler. To test them in isolation you need a tiny Angular environment. TestBed is Angular's primary testing utility that builds this environment for each test.

It configures a temporary NgModule, compiles your component, and gives you a handle to interact with it.

configureTestingModule

TestBed.configureTestingModule() declares what your test needs: the component under test, its providers, and any imports. For standalone components you put the component itself in imports.

import { TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [CounterComponent],
  });
});

Creating a Component Fixture

TestBed.createComponent(CounterComponent) returns a ComponentFixture. The fixture is your remote control: it wraps the component instance, its native DOM element, and the change-detection machinery.

import { ComponentFixture, TestBed } from '@angular/core/testing';

let fixture: ComponentFixture<CounterComponent>;

beforeEach(() => {
  fixture = TestBed.createComponent(CounterComponent);
});

Accessing the Component Instance

fixture.componentInstance is the actual class instance. You can call its methods and read its properties directly, just like normal TypeScript.

it('creates the component', () => {
  const fixture = TestBed.createComponent(CounterComponent);
  const component = fixture.componentInstance;
  expect(component).toBeTruthy();
  expect(component.count).toBe(0);
});

detectChanges Triggers Rendering

A freshly created fixture has NOT rendered yet. Call fixture.detectChanges() to run change detection and the component's ngOnInit, binding data into the DOM.

it('renders initial value', () => {
  const fixture = TestBed.createComponent(CounterComponent);
  fixture.detectChanges(); // now bindings are applied
  const el = fixture.nativeElement as HTMLElement;
  expect(el.textContent).toContain('0');
});

nativeElement vs debugElement

fixture.nativeElement is the raw DOM node (an HTMLElement). fixture.debugElement is Angular's richer wrapper that lets you query by directive, read injected services, and inspect bindings.

const native = fixture.nativeElement;       // HTMLElement
const debug = fixture.debugElement;         // DebugElement
console.log(debug.componentInstance === fixture.componentInstance); // true

Providers in the Testing Module

If the component injects services, supply them through providers. You can use real services or test doubles. Here we provide a real service for a simple case.

TestBed.configureTestingModule({
  imports: [CounterComponent],
  providers: [
    { provide: LoggerService, useValue: { log: () => {} } },
  ],
});

compileComponents for External Templates

When using non-inline templateUrl/styleUrls without the Angular CLI test setup, templates must be compiled async. Call await TestBed.compileComponents(). With the CLI this is usually automatic.

beforeEach(async () => {
  await TestBed.configureTestingModule({
    imports: [ProfileComponent],
  }).compileComponents();
});

A Complete Minimal Test

Putting it together: configure, create, detect, assert. This is the canonical shape of nearly every Angular component test.

describe('CounterComponent', () => {
  let fixture: ComponentFixture<CounterComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({ imports: [CounterComponent] });
    fixture = TestBed.createComponent(CounterComponent);
    fixture.detectChanges();
  });

  it('starts at zero', () => {
    expect(fixture.componentInstance.count).toBe(0);
  });
});

TestBed.inject for Services

To grab a configured provider, use TestBed.inject(Token). This is the modern replacement for the deprecated TestBed.get().

const logger = TestBed.inject(LoggerService);
expect(logger).toBeDefined();

Resetting Between Tests

TestBed automatically resets its module before each test, so providers and component state do not leak. This is why you configure inside beforeEach rather than once globally.

Quick Check

Test what happens right after createComponent.

Recap

You learned the testing core: TestBed.configureTestingModule() builds the environment, createComponent() returns a ComponentFixture, and detectChanges() renders it. Use componentInstance for the class, nativeElement/debugElement for the DOM, and TestBed.inject() for services.

Free to start

Learn HTML with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
38
Lessons
144

Frequently Asked Questions

Is the “TestBed and Component Fixtures” lesson free?

Yes — any 3 lessons of the Angular Academy learning path, including “TestBed and Component Fixtures”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Angular Academy course includes 4 lessons in total.

What will I learn in “TestBed and Component Fixtures”?

Configure and create components in tests. You practise Angular Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Angular Academy?

No prior experience is required. Angular Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “TestBed and Component Fixtures” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Angular Academy lesson?

Yes. Every Angular Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. TestBed and Component Fixtures
  2. Testing Inputs, Outputs, and DOM
  3. Mocking Services and Dependencies
  4. Testing Signals and Async Code
← Back to Angular Academy