Sub topic 11
Testing a Directive with a Host Component
This chapter assumes you can write an attribute directive with the host metadata property and signal inputs (the earlier chapters cover this). It also assumes you know basic TestBed usage and a test runner with describe, it, and expect, such as Jasmine or Jest. The examples run in a browser-like DOM.
Why a directive needs a host component
A directive has no template, so there is nothing to render when you test it alone. It also does nothing until Angular attaches it to an element. You could construct the class with new HighlightDirective(), but the inject() calls would fail outside an injection context. Even if they worked, you would only be testing the class and not Angular's wiring. The wiring is where most directive bugs live: the selector, the input alias, the host bindings, and the events.
The standard approach is to write a small component only for the test. Its template uses the directive on a real element, and you drive that element the way a user would.
| What you want to verify | How the host component helps |
|---|---|
| The selector matches | The directive only runs if the template attribute matches. |
| The input alias works | You bind through the same attribute name that real templates use. |
| Host bindings update the DOM | You read the real element's `style` or attributes after change detection. |
| Host listeners fire | You dispatch real DOM events on the element. |
| Outputs emit | The host template handles the event and records it. |
The directive under test
These tests use the directive from the inputs chapter. The host metadata declares one style binding and two listeners. A signal input shares the selector name through an alias.
import { Directive, input, signal } from '@angular/core';
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'active() ? (color() || "yellow") : null',
'(mouseenter)': 'active.set(true)',
'(mouseleave)': 'active.set(false)',
},
})
export class HighlightDirective {
color = input('', { alias: 'appHighlight' });
active = signal(false);
}Behavior to pin down:
- With no hover, the element has no background color.
- While hovering, the color is the input value, or yellow if the input is empty.
- After the pointer leaves, the color is removed.
The first 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 test follows four steps:
TestBed.createComponentbuilds the host component and attaches the directive to the<p>.querySelectorfinds the element the directive is attached to.dispatchEventtriggers the(mouseenter)listener, which sets theactivesignal.fixture.detectChanges()makes Angular re-evaluate the[style.backgroundColor]host binding and write the style.
The host component is declared in the same file as the test and is not exported. This keeps the test self-contained, and Angular's compiler handles the unexported class fine in tests.
Testing every branch
One host component can contain several elements, so the same fixture covers the default color, the custom color, and the leave behavior.
import { Component } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { HighlightDirective } from './highlight.directive';
@Component({
imports: [HighlightDirective],
template: `
<p id="default" appHighlight>Default</p>
<p id="custom" appHighlight="lightblue">Custom</p>
<p id="plain">No directive</p>
`,
})
class MultiHostComponent {}
describe('HighlightDirective branches', () => {
let fixture: ComponentFixture<MultiHostComponent>;
let root: HTMLElement;
const el = (id: string) => root.querySelector('#' + id) as HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(MultiHostComponent);
root = fixture.nativeElement as HTMLElement;
fixture.detectChanges();
});
it('has no background before hovering', () => {
expect(el('default').style.backgroundColor).toBe('');
});
it('falls back to yellow when no value is given', () => {
el('default').dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
expect(el('default').style.backgroundColor).toBe('yellow');
});
it('removes the color on mouseleave', () => {
const custom = el('custom');
custom.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
custom.dispatchEvent(new Event('mouseleave'));
fixture.detectChanges();
expect(custom.style.backgroundColor).toBe('');
});
it('does not touch elements without the directive', () => {
el('plain').dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
expect(el('plain').style.backgroundColor).toBe('');
});
});The last test is a negative case: it checks the directive does not leak onto other elements. Tests like this catch a selector that is too broad.
Calling fixture.detectChanges() in beforeEach runs the first change detection pass. Host bindings are applied during that pass, so call it before you read any initial state.
Changing inputs after creation
Real templates bind inputs to values that change. To test that, give the host component a signal and bind it. Updating the signal then simulates a parent changing the value.
import { Component, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { HighlightDirective } from './highlight.directive';
@Component({
imports: [HighlightDirective],
template: `<p [appHighlight]="color()">Text</p>`,
})
class DynamicHostComponent {
color = signal('lightblue');
}
describe('HighlightDirective with a changing input', () => {
it('follows the bound color', () => {
const fixture = TestBed.createComponent(DynamicHostComponent);
const p = fixture.nativeElement.querySelector('p') as HTMLElement;
p.dispatchEvent(new Event('mouseenter'));
fixture.detectChanges();
expect(p.style.backgroundColor).toBe('lightblue');
fixture.componentInstance.color.set('pink');
fixture.detectChanges();
expect(p.style.backgroundColor).toBe('pink');
});
});Do not try to set the directive's input directly, for example directive.color = .... Signal inputs are read-only from outside, and bypassing the template skips the path your users take. Always change the value through the host.
Reading the directive instance
Sometimes the DOM is not enough, and you want to check internal state, such as whether active() is true. Use DebugElement with the By.directive predicate to find the element and get the instance.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HighlightDirective } from './highlight.directive';
@Component({
imports: [HighlightDirective],
template: `<p appHighlight>Text</p>`,
})
class InstanceHostComponent {}
describe('HighlightDirective instance', () => {
it('tracks hover state', () => {
const fixture = TestBed.createComponent(InstanceHostComponent);
const debugEl = fixture.debugElement.query(By.directive(HighlightDirective));
const directive = debugEl.injector.get(HighlightDirective);
expect(directive.active()).toBe(false);
debugEl.triggerEventHandler('mouseenter');
expect(directive.active()).toBe(true);
});
});By.directive also helps count matches: fixture.debugElement.queryAll(By.directive(HighlightDirective)).length. triggerEventHandler calls the listeners Angular registered on that element without creating a real DOM event, which is faster but does not exercise the browser's event path. Prefer dispatchEvent for behavior and triggerEventHandler for quick state checks.
Testing outputs
An output is tested by handling it in the host template and recording what arrives. The click-outside directive from the outputs chapter listens on document, so the test dispatches real clicks that bubble up to it.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ClickOutsideDirective } from './click-outside.directive';
@Component({
imports: [ClickOutsideDirective],
template: `
<div id="panel" appClickOutside (clickOutside)="count = count + 1">
<button id="inside">Inside</button>
</div>
<button id="outside">Outside</button>
`,
})
class ClickHostComponent {
count = 0;
}
describe('ClickOutsideDirective', () => {
it('emits only for clicks outside the host', () => {
const fixture = TestBed.createComponent(ClickHostComponent);
fixture.detectChanges();
const root = fixture.nativeElement as HTMLElement;
(root.querySelector('#inside') as HTMLElement).click();
expect(fixture.componentInstance.count).toBe(0);
(root.querySelector('#outside') as HTMLElement).click();
expect(fixture.componentInstance.count).toBe(1);
});
});HTMLElement.click() creates an event that bubbles, so it reaches the document:click listener. A bare new Event('click') does not bubble unless you pass { bubbles: true }, and the directive would never see it. TestBed attaches the fixture's root element to the document, which is why a document-level listener works here.
Common test mistakes
- Forgetting
detectChanges(). The listener runs immediately, but host bindings update only during change detection. The style stays unchanged and the assertion fails, which looks like a directive bug. - Forgetting the
importsarray. Without the directive in the host'simports, the attribute is ignored and no error is raised for a plain attribute. The test fails with an unchanged element. For a bound input like[appHighlight], Angular reports an unknown property. - Non-bubbling events. Events for
document:orwindow:listeners must bubble. Use.click()or pass{ bubbles: true }. - Asserting on a color format. Browsers normalize some values.
'#ff0000'may read back as'rgb(255, 0, 0)'. Named colors such aslightblueare safe, or compare with the format the browser returns. - Sharing state between tests. Create a fresh fixture in each test or in
beforeEach. Directive state such asactivelives on the instance, so reuse leaks hover state from one test to the next.
Exercise
A test dispatches new Event('mouseenter') on an element that has appHighlight="lightblue", then immediately asserts p.style.backgroundColor equals 'lightblue'. The assertion fails with an empty string, although the directive works in the browser. What is missing, and why does the browser not need it?
Show answer
The test never calls fixture.detectChanges() after dispatching the event. The listener sets the active signal, but the [style.backgroundColor] host binding is applied only when change detection runs. In the browser, Angular runs change detection automatically after the event, so the style updates. In a test, you must trigger it yourself (or await fixture.whenStable() in a zoneless setup).
Exercise
Write the host component template and the key assertion for testing that a (clickOutside) output does not fire when the user clicks a child of the host element.
Show answer
Template: <div appClickOutside (clickOutside)="count = count + 1"><button id="inside">Inside</button></div>, with a count = 0 field on the host class. Test: call (root.querySelector('#inside') as HTMLElement).click(); and assert expect(fixture.componentInstance.count).toBe(0);. The click bubbles to document, the directive checks contains(event.target), finds the target inside the host, and does not emit.