0
0
AngularHow-ToBeginner · 4 min read

How to Use TestBed in Angular for Unit Testing

Use TestBed in Angular to configure and create a testing module that mimics your app module. It allows you to declare components, provide services, and compile components for unit testing in an isolated environment.
📐

Syntax

TestBed is used to configure a testing module with configureTestingModule. You declare components, import modules, and provide services inside it. Then you call compileComponents() to prepare components for testing. Finally, use TestBed.createComponent() to create a component instance for tests.

typescript
TestBed.configureTestingModule({
  declarations: [MyComponent],
  imports: [SomeModule],
  providers: [MyService]
}).compileComponents();

const fixture = TestBed.createComponent(MyComponent);
const component = fixture.componentInstance;
💻

Example

This example shows how to test a simple Angular component using TestBed. It sets up the testing module, creates the component, triggers change detection, and checks the rendered output.

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

@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 display greeting', () => {
    const fixture = TestBed.createComponent(HelloComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement as HTMLElement;
    expect(compiled.querySelector('h1')?.textContent).toBe('Hello, Angular!');
  });
});
Output
Test passes if the <h1> contains 'Hello, Angular!'
⚠️

Common Pitfalls

  • Forgetting to call compileComponents() before creating components can cause errors.
  • Not importing required modules or declaring components leads to missing dependencies.
  • Creating components outside beforeEach can cause stale instances.
  • Not calling fixture.detectChanges() means template bindings won't update.
typescript
/* Wrong way: Missing compileComponents and detectChanges */
TestBed.configureTestingModule({
  declarations: [MyComponent]
});
const fixture = TestBed.createComponent(MyComponent);
// fixture.detectChanges() missing

/* Right way: */
await TestBed.configureTestingModule({
  declarations: [MyComponent]
}).compileComponents();
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
📊

Quick Reference

  • configureTestingModule: Set up declarations, imports, providers.
  • compileComponents: Prepare components asynchronously.
  • createComponent: Create component fixture for testing.
  • fixture.detectChanges: Update template bindings.

Key Takeaways

Always configure TestBed with declarations, imports, and providers before tests.
Call compileComponents() before creating component instances to avoid errors.
Use fixture.detectChanges() to update the component template after changes.
Create components inside beforeEach to get fresh instances for each test.
TestBed simulates Angular modules to isolate and test components or services.