Interpolation: Checking Bound Values in the Template

This test verifies that the component correctly binds values into the template. Remember to invoke fixture.detectChanges() — this call triggers the TestBed to run data binding and refresh the rendered view.


Handling User Input Value Changes

This scenario confirms that typing into a text field updates the corresponding property in the component class. Note the usage of fakeAsync and tick here, as form bindings rely on asynchronous execution under the hood.


Triggering Click Events on HTML Elements


Interacting with Nested Child Components

Imagine our component embeds a child component within its template:

<app-nested-component></app-nested-component>

The child component can be reached and manipulated directly in tests like so:


Testing Content Projection

Content projection requires a bit more setup. To test it, you need to create a host wrapper component around your target component and use that wrapper to feed projected content through. First, let's add projected content to our component's view:

<div class="projected-content> 
    <ng-content select="[description]"></ng-content>
</div>

We can then verify it works by introducing a ExampleWrapperComponent as shown here:


Verifying Component Inputs and Outputs

Component inputs can be tested just like any other class property. Outputs, on the other hand, can be spied upon, allowing you to assert that they emit the expected payload.


Handling Component Dependencies

Components often rely on external services to function correctly, and they need to communicate with those services during runtime. In unit tests, you must supply these dependencies in the TestBed configuration so your tests run smoothly. There are two distinct scenarios to consider:

Services Provided at the Root Injector Level

If your component injects a service registered in the root injector, you'll need to include that service in the TestBed providers so it's available during test execution:

Notice that we're using a mock implementation here—it's simpler and safer to control in tests. Once configured, you can retrieve that service in your test file by invoking the inject method on the TestBed.

Services Provided via the Component Injector

When a dependency is registered at the component level, the TestBed cannot reach it directly, as it only exists lower in the injection hierarchy. In this case, you must override the component's providers to supply the dependency, and then access it through the component's own injector.


Is there a testing scenario you need that isn't listed here? Drop a comment below, and we'll be happy to add a dedicated use case for it.