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 good idea of how to proceed when testing them.
Consider the copyright.directive.ts file that we created in Chapter 5, Enriching 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 with a component, so it makes sense to unit test it while using it on a component. Let’s create a test host component and add it to the imports array of the...
 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                