lundi 10 juin 2019

How to test directive in angular 7 using jasmine?

I have made a directive in angular for button label but I do not know how to test angular directive in which constructor have elementRef.

Directive looks like

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
    // tslint:disable-next-line:directive-selector
    selector: '[lstA11yIonButton]'
})

export class LstA11yIonButtonDirective {
    @Input() lstA11yLabel: string;

    constructor(
        private el: ElementRef
    ) {
        el.nativeElement.componentOnReady().then(() => {
            this.onShadowReady();
        });
    }

    onShadowReady() {
        const button = this.el.nativeElement.shadowRoot.querySelector('button');
        button.setAttribute('aria-label', this.lstA11yLabel);
    }
}

Test case written by me looks like this but it does not cover the code in code-coverage

import { LstA11yIonButtonDirective } from './lst-a11y-ion-button.directive';
import { ElementRef, Component, DebugElement } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

@Component({
    template: `
        <button
            type="button"
            class="button"
            lstA11yIonButton
            [lstA11yLabel]="'button-label'"
        ></button>
    `
})
class TestComponent {}

describe('Directive: A11yLabelDirective', () => {
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;
    let inputEl: DebugElement;
    const elementRef: ElementRef = null;
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [LstA11yIonButtonDirective, TestComponent]
        });
        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        spyOn(elementRef.nativeElement, 'componentOnReady');
        inputEl = fixture.debugElement.query(By.all());
    });

    it('should create component', () => {
        expect(component).toBeDefined();
    });

    it('should set button label', () => {
        const debugEl: HTMLElement = fixture.debugElement.nativeElement;
        const button: HTMLElement = debugEl.querySelector('button');
    });
});

How to test such a type of directive in angular 7 with jasmine ?

Aucun commentaire:

Enregistrer un commentaire