Show List

Angular Test Bed (ATB) and ComponentFixture

Angular Test Bed (ATB) is testing framework that allows to easily create components, handle injection, test asynchronous functions and interact with the application. Test bed is helpful to :
  • Test the interaction of component with HTML template
  • Test with change detection
  • Test Dependency Injection
  • Test using NgModule


Here is an example of a test suite using Testbed:

In the beforeEach function, testing module is configured using Test bed. This configuration is similar to a normal ngModule with declarations, imports and providers. We can use this test Angular Module to instantiate components, inject dependencies etc.

home.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { HomeComponent } from './home.component';
import { RouterTestingModule } from "@angular/router/testing";
import { FormsModule } from '@angular/forms';

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule,
        FormsModule],
      declarations: [HomeComponent]
    })
      .compileComponents();

    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

ComponentFixture

Fixture is a wrapper for a component. Component or service instance can be created using Test bed. Fixture also provides access to the HTML element on the page. Example:

  let component: GreetComponent;
  let fixture: ComponentFixture<GreetComponent>;
  let el: DebugElement;

  // create component and test fixture
  fixture = TestBed.createComponent(GreetComponent);
  // Get the component
  component = fixture.componentInstance;
  // Get the HTML element by CSS selector (e.g., by class name)
  el = fixture.debugElement.query(By.css('#msgHead'));

Source Code:
https://github.com/it-code-lab/angular-application

    Leave a Comment


  • captcha text