0
0
Angularframework~5 mins

TestBed configuration in Angular

Choose your learning style9 modes available
Introduction

TestBed helps you set up and test Angular components and services easily. It creates a small Angular environment for your tests.

When you want to test an Angular component's behavior.
When you need to test a service with dependencies.
When you want to check how Angular modules work together in a test.
When you want to simulate Angular's dependency injection in tests.
When you want to test Angular directives or pipes.
Syntax
Angular
TestBed.configureTestingModule({
  declarations: [MyComponent],
  imports: [MyModule],
  providers: [MyService]
}).compileComponents();

declarations is for components, directives, and pipes you want to test.

imports is for Angular modules your component depends on.

Examples
Basic setup to test a single component.
Angular
TestBed.configureTestingModule({
  declarations: [MyComponent]
}).compileComponents();
Setup including a module needed for forms.
Angular
TestBed.configureTestingModule({
  declarations: [MyComponent],
  imports: [FormsModule]
}).compileComponents();
Setup to test a service with dependency injection.
Angular
TestBed.configureTestingModule({
  providers: [MyService]
});
Sample Program

This test sets up TestBed with a simple component. It checks if the component creates and shows the correct text.

Angular
import { TestBed } from '@angular/core/testing';
import { Component } from '@angular/core';

@Component({
  selector: 'app-hello',
  template: '<h1>Hello {{name}}</h1>'
})
class HelloComponent {
  name = 'Angular';
}

describe('HelloComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [HelloComponent]
    }).compileComponents();
  });

  it('should create the component and display name', () => {
    const fixture = TestBed.createComponent(HelloComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement as HTMLElement;
    expect(compiled.querySelector('h1')?.textContent).toBe('Hello Angular');
  });
});
OutputSuccess
Important Notes

Always call compileComponents() when testing components to compile templates.

You can add imports to include Angular modules your component needs.

Use providers to add services or mocks for dependency injection.

Summary

TestBed configures a mini Angular environment for testing.

Use declarations, imports, and providers to set up what your test needs.

Call compileComponents() to prepare components before testing.