...

/

The TestBed Class

The TestBed Class

Learn what TestBed class is, how we can inject services into the TestBed class, and what benefits it brings to our application.

What is the TestBed class?

The Angular TestBed class helps us by providing an environment for testing our application. It also provides an API for making our components and services available to the Unit Tests.

In AngularJS, we didn’t have the TestBed class, which made it far more complex to access the Controllers and services in the Unit Tests. Thankfully, with the TestBed class, it is far easier to access our components and services in order to test them.

Going back to our example spec file, let’s see how the TestBed class is being used.

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

import { MyCompComponent } from './my-comp.component';

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ MyCompComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyCompComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

In the two beforeEach() functions, which, as we know, are run before each test spec within the file, we are using the TestBed to make the component we’re testing accessible.

First beforeEach() function

In the first beforeEach(), the TestBed is being configured through calling its configureTestingModule() method. This tells the test environment’s module of all the declarations it needs to know. This is similar to how the main app.module.ts is set up. If we go back to what we learned about the main NgModule class in ...