Testing directives
Directives are usually quite straightforward in their overall shape, being components with no view attached. The fact that directives usually work with components gives us a very good idea of how to proceed when testing them.
Consider the copyright.directive.ts
file that we created in Chapter 5, Enrich Applications using Pipes and Directives:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appCopyright]'
})
export class CopyrightDirective {
constructor(el: ElementRef) {
const currentYear = new Date().getFullYear();
const targetEl: HTMLElement = el.nativeElement;
targetEl.classList.add('copyright');
targetEl.textContent = 'Copyright ©${currentYear} All Rights Reserved.';
}
}
A directive is usually used in conjunction with a component, so it makes sense to unit test it while using it on a component. Let’s create a test host component...