Testing single use cases of directive is unlikely to explore the full range of its capabilities.
Since directives tend to manipulate the DOM, class-only tests might not be helpful either.
A better solution is to create an artificial test component that demonstrates all ways to apply the directive. (Create it inside the .
spec
file)
@Direcive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnChanges {
private elementRef = inject(ElementRef);
private renderer = inject(Renderer2);
highlightColor = input('');
ngOnChanges(changes: SimpleChanges): void {
this.renderer.setStyle(
this.elementRef.nativeElement,
'background-color',
this.highlightColor()
);
}
}
highlight.directive.specs.ts
@Component({
})
// Created component for Test purposes
export class TestComponent{
colorName = 'blue';
}
describe('HighlightDirective', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TestComponent]
}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChange();
});
it('should create an instance of Test Component', () => {
expect(component).toBeTruthy();
});
it('should change background color based on directive param', () => {
const expectedColor = 'red';
component.colorName = expectedColor;
fixture.detectChanges();
const elementDirective = fixture.debugElement.query(By.css('span')).nativeElement as HTMLElement;
expect(elementDirective.style.backgroundColor).toBe(expectedColor);
});
});