Sub topic 11
Testing a Directive with a Host Component
This chapter assumes you can write a standalone attribute directive with host metadata and a signal input, as in the earlier chapters. It also assumes you know basic describe/it/expect syntax from Jasmine or Jest. We test the HighlightDirective from the inputs chapter.
Why a host component
A directive does nothing on its own. It needs an element to attach to. You could instantiate the class with new, but then Angular would not process host bindings, inputs, or event listeners. Those features are what you want to verify.
The standard approach is a small test-only component that uses the directive in its template. You create that component with TestBed, interact with the rendered element, and check the result. The test then exercises the directive the way a real application does.
The basic test
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { HighlightDirective } from './highlight.directive';
@Component({
imports: [HighlightDirective],
template: `<p appHighlight="lightblue">Text</p>`,
})
class TestHostComponent {}
describe('HighlightDirective', () => {
it('applies the color while hovering', () => {
const fixture = TestBed.createComponent(TestHostComponent);
const p = fixture.nativeElement.querySelector('p') as HTMLElement;
p.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
expect(p.style.backgroundColor).toBe('lightblue');
});
});The host component is declared in the spec file and is not exported. It is standalone, so it lists the directive in imports, just like production code. Nothing needs to be declared in TestBed.configureTestingModule for a standalone component.
The test follows three steps:
- Dispatch a DOM event on the element. The directive's
(mouseenter)host listener reacts to it and setsactivetotrue. - Call
fixture.detectChanges(). Host bindings are only re-evaluated during change detection, so the style is not written until this runs. - Assert on the real element.
style.backgroundColoris what a user would see.
Testing the reset and the default
Each behavior deserves its own test. Put shared setup in beforeEach so the tests stay short.
describe('HighlightDirective states', () => {
let p: HTMLElement;
let fixture: ComponentFixture<TestHostComponent>;
beforeEach(() => {
fixture = TestBed.createComponent(TestHostComponent);
p = fixture.nativeElement.querySelector('p') as HTMLElement;
fixture.detectChanges();
});
it('has no background before hovering', () => {
expect(p.style.backgroundColor).toBe('');
});
it('removes the background on mouseleave', () => {
p.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
p.dispatchEvent(new Event('mouseleave'));
fixture.detectChanges();
expect(p.style.backgroundColor).toBe('');
});
});This block also needs import { ComponentFixture, TestBed } from '@angular/core/testing';. The initial detectChanges() in beforeEach renders the template and applies the first round of bindings.
Testing the default color and a changing input
To check the yellow fallback, use a second host component with no value. To check that the input reacts to changes, bind it to a signal on the host.
import { Component, signal } from '@angular/core';
@Component({
imports: [HighlightDirective],
template: `
<p id="plain" appHighlight>Default</p>
<p id="dynamic" [appHighlight]="color()">Dynamic</p>
`,
})
class MultiHostComponent {
color = signal('lightblue');
}
it('falls back to yellow and follows input changes', () => {
const fixture = TestBed.createComponent(MultiHostComponent);
const root = fixture.nativeElement as HTMLElement;
const plain = root.querySelector('#plain') as HTMLElement;
const dynamic = root.querySelector('#dynamic') as HTMLElement;
plain.dispatchEvent(new Event('mouseenter'));
dynamic.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
expect(plain.style.backgroundColor).toBe('yellow');
expect(dynamic.style.backgroundColor).toBe('lightblue');
fixture.componentInstance.color.set('pink');
fixture.detectChanges();
expect(dynamic.style.backgroundColor).toBe('pink');
});Putting several elements in one host keeps the number of throwaway components low.
Common errors
| Symptom | Likely cause |
|---|---|
| Style is still empty after the event | `fixture.detectChanges()` was not called after dispatching the event |
| `NG0303` or "not a known property" error | The directive is missing from the host component's `imports` |
| `querySelector` returns `null` | The first `detectChanges()` has not run, or the selector does not match the template |
| Event listener never fires | The event name differs from the one in `host`, for example `click` instead of `mouseenter` |
Exercise
A test dispatches mouseenter on an element that uses HighlightDirective, then immediately asserts p.style.backgroundColor equals 'yellow'. The assertion fails with an empty string, although the directive works in the browser. What is missing, and why?
Show answer
The test must call fixture.detectChanges() after dispatching the event. The listener sets the active signal, but the [style.backgroundColor] host binding is only evaluated during change detection. In the browser the application triggers change detection for you. In a test you trigger it yourself.
Exercise
Write the template for a host component that lets you test that appHighlight with no value falls back to yellow. Which array must include the directive?
Show answer
Template: <p appHighlight>Text</p>. The host component's imports array must include HighlightDirective. Without it, Angular treats appHighlight as a plain attribute and the directive never runs.