lundi 24 juin 2019

How test directive with Renderer2?

I have created a small directive that prevents default of event(s) passed to it.

@Directive({
    selector: '[sPreventDefault]'
})
export class PreventDefaultDirective {
    private events: (() => void)[] = [];
    @Input('sPreventDefault') set listenOn(events: string | string[]) {
        this.removeListeners();

        if (typeof events == 'string') {
            events = [events];
        }
        this.registerEventListener(
            events,
            e => {
                if (e instanceof Event) {
                    e.stopPropagation();
                } else {
                    e.srcEvent.stopPropagation();
                }
            },
        );
    }

    constructor(private elementRef: ElementRef<HTMLElement>, private renderer: Renderer2) {
        super(elementRef, renderer);
    }

    protected registerEventListener(listenOn: string[], eventListener: (e: Event | HammerJSEvent) => void): void {
        this.events = listenOn.map(eventName => {
            return this.renderer.listen(this.elementRef.nativeElement, eventName, eventListener);
        });
    }
    protected removeListeners(): void {
        this.events.forEach(dispose => dispose());
        this.events = [];
    }
}

Test suit

@Component({
    selector: 'test-host',
    template: `<div [sPreventDefault]="events">`,
})
class TestHostComponent {
    @ViewChild(PreventDefaultDirective) directive!: PreventDefaultDirective;
    @Input() events: PreventDefaultDirective['listenOn'] = [];
}

fdescribe('PreventDefaultDirective', () => {
    let host: TestHostComponent;
    let hostElement: DebugElement;
    let fixture: ComponentFixture<TestHostComponent>;
    let directive: PreventDefaultDirective;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                TestHostComponent,
                PreventDefaultDirective,
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(TestHostComponent);
        hostElement = fixture.debugElement;
        host = fixture.componentInstance;
        directive = host.directive;
    }));

    it('should create an instance', () => {
        host.events = ['testEvent'];
        fixture.detectChanges();
        expect(directive).toBeTruthy();
    });

    it('should add listener', () => {
        host.events = ['testEvent'];
        fixture.detectChanges();

        //  DebugElement.listeners is null
        expect(hostElement.listeners.length).toBe(1);
        expect(hostElement.listeners.map(l => l.name)).toBe(host.events);
    });
});

My problem is, that DebugElement, does not seems to know about events registered via Renderer2.listen method. What is the right way to test this?

Aucun commentaire:

Enregistrer un commentaire