kdocs
GitHub
Lang - Web
Lang - Web
  • Base
    • Css
    • Javascript
    • Typescript
      • New Project
  • Frameworks
    • Angular
      • Directives
      • Components
      • Templates
        • Bindings
        • Control Flow
        • Variables
      • Signals
      • Pipes
      • Services
        • Dependency Injection
      • Forms
        • Reactive Form
        • Template-Driven Form
      • Router
      • HTTP Client
      • Observables RxJS
      • Testing
        • Components
        • Directives
        • Pipes
        • Services
      • Optimization & Performance
      • Security
Powered by GitBook
On this page
  1. Frameworks
  2. Angular
  3. Testing

Directives

PreviousComponentsNextPipes

Last updated 5 months ago

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)

highlight.directive.ts
@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);
    });
});

AngularAngular
testing-attribute-directives
Logo