Testing with Inputs and Outputs
Learn how to test inputs and outputs by verifying the input binding and output binding triggers.
We'll cover the following...
We will now learn how to test the public API of a component. So far, we have learned how to test components with simple properties and tackle synchronous and asynchronous dependencies. But there is more to a component than that. As we learned, a component has a public API consisting of inputs and outputs that should be tested as well.
Since we want to test the public API of a component, it makes sense to test how it interacts when hosted from another component. Testing such a component can be done in two ways:
We can verify that our input binding is correctly set.
We can verify that our output binding triggers correctly and that what it emits is received.
Verifying input and output bindings
Suppose that we have the following bindings.component.ts
file with an input and output binding:
import { Component, Input, Output, EventEmitter } from '@angular/core';@Component({selector: 'app-bindings',template: `<p>{{title}}</p><button (click)="liked.emit()">Like!</button>`})export class BindingsComponent {@Input() title = '';@Output() liked = new EventEmitter();}
Before we start writing our tests, we should create a test host component that is going to use the component under test:
@Component({template: `<app-bindings [title]="testTitle" (liked)="isFavorite = true"></app-bindings>`})export class TestHostComponent {testTitle = 'My title';isFavorite = false; }
In the setup phase, we declare both components in the testing module on lines 7–8, but notice that the ComponentFixture
is of the TestHostComponent
type on line 12:
let component: TestHostComponent;let fixture: ComponentFixture<TestHostComponent>;beforeEach(async () => {await TestBed.configureTestingModule({declarations: [BindingsComponent,TestHostComponent]});fixture = TestBed.createComponent(TestHostComponent);component = fixture.componentInstance;fixture.detectChanges();});
We follow this approach because we want to test BindingsComponent
when used with a host component, ...