Member-only story

Testing Angular Directives

Josh Hicks
5 min readDec 9, 2018

Using HTMLElement

The Goal

In this example I wanted to show you how you can dive down into the DOM to find elements in your Angular templates. This can be used to make sure your Angular directives are working properly when writing tests. In order to do this we’ll be tapping into the power of the HTMLElement API. This will make it possible to manipulate and read properties of elements in our component’s HTML template.

* NOTE: This article is not meant to be a full scale tutorial on how to do testing in Angular . For more information on that try this.

What Angular’s testing module gives you

By default, Angular comes with some great utility classes to use while writing tests. These can mostly be imported from @angular/core/testing however, there are other tools you can use like the By class which can also be used to query the DOM. This can be found in @angular/platform-browser .

The main class we’ll be discussing in this example is the ComponentFixture class. This class acts as a wrapper around our actual component that comes with some added behavior. A Fixture has a property that exposes out component’s HTML as a nativeElement , which is exactly what we need to start interacting with the DOM.

--

--

Josh Hicks
Josh Hicks

Written by Josh Hicks

Software engineer, writer, traveler, weight lifter

Responses (2)