Post

Angular 2 Component Testing Template Using TestBed

Below is a template for using TestBed to test Angular 2 components.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { async, TestBed } from '@angular/core/testing';

import { SomeComponent } from './some.component';

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [
      SomeComponent
    ],
    imports: [
      // HttpModule, etc.
    ],
    providers: [
      // { provide: ServiceA, useClass: TestServiceA }
    ]
  });
});

it('should do something', async(() => {
  // Overrides here, if you need them
  TestBed.overrideComponent(SomeComponent, {
    set: {
      template: '<div>Overridden template here</div>'
      // ...
    }
  });

  TestBed.compileComponents().then(() => {
    const fixture = TestBed.createComponent(SomeComponent);

    // Access the dependency injected component instance
    const app = fixture.componentInstance;

    expect(app.something).toBe('something');

    // Access the element
    const element = fixture.nativeElement;

    // Detect changes as necessary
    fixture.detectChanges();

    expect(element.textContent).toContain('something');
  });
}));

For a template showing MockBackend usage while testing a service with TestBed, see Angular 2 MockBackend Service Testing Template Using TestBed.

This post is licensed under CC BY 4.0 by the author.