Performing Component Binding in Angular Tests

Scenario

The Angular Component Testing Scenarios ComponentBanner binds the title property dynamically to an h1 element within the template.

@Component({
selector: 'app-banner',
template: '<h1>{{title}}</h1>',
styles: ['h1 { color: green; font-size: 350%}'],
})
export class BannerComponent {
title = 'Test Tour of Heroes';
}

And we want to verify that the title property is bound to the h1 element innerText .

Approach

Call fixture.detectChanges() .

it('should display original title', () => {
fixture.detectChanges();
expect(h1.textContent).toContain(component.title);
});

Calling detectChanges() on the fixture triggers the component binding within Angular tests.

Creating the component fixture = TestBed.createComponent(BannerComponent) does not perform component binding by itself, thus the h1 element will be empty prior to the fixture.detectChanges() call.

it('no title in the DOM after createComponent()', () => {
expect(h1.textContent).toEqual('');
});

Demo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation