Test parent and child components when passing data with input binding

Angular supports the decomposition of components by allowing you to include one into another. To test a component that contains other elements you have to declare them in the test configuration. Don’t forget about any @Input property of an aggregated component or running the test suite will result with the following error:

Template parse errors: Can't bind to property since it isn't a known property of component

The components

Let’s use the following two components from the official Angular documentation.

The first one is the HeroChildComponent that receives a hero instance from the parent component and displays it in a header:

The second one is the HeroParentComponent that passes the hero instance to the <app-hero-child> element:

Test the parent component with input binding

The test for the HeroParentComponent will succeed if we declare in it the child component – including the property that is passed with @Input:

The following file contains the full test file for HeroParentComponent:

Test the child component

Without mocking the hero property in the child component, the test suite fails with the following error:

HeroChildComponent should create
[object ErrorEvent] thrown

You can simply create the mock for hero like this:

The following file contains the full test file for HeroChildComponent:

Photo by Daria Shevtsova on StockSnap

Leave a Reply

Your email address will not be published. Required fields are marked *