簡體   English   中英

在Angular 7指令上測試@HostListening('error')

[英]Testing @HostListening('error') on Angular 7 directive

我們有一個可以通過ID查找的徽標存儲庫,但是有一些實例會丟失它們,我們需要顯示一個“默認”徽標。 我制定了一個角度指令,使這個過程更容易一些。 它的使用方式如下:

<img [appLogoFromId]="item.id"/>

這是功能指令

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

@Directive({
    selector: '[appLogoFromId]'
})
export class LogoFromIdDirective {
    private static readonly baseUrl: string = 'https://our-website.com/sitelogos/';
    private static readonly fallbackImgUrl: string = LogoFromIdDirective.baseUrl + 'default.svg';

    @Input() set appLogoFromId(value: string | number) {
        this.nativeEl.src = LogoFromIdDirective.baseUrl + value + '.jpg';
    }

    private readonly nativeEl: HTMLImageElement;
    private errCount: number = 0;

    constructor(private elem: ElementRef) {
        this.nativeEl = this.elem.nativeElement;

        //This directive only works on <img> elements, so throw an error otherwise
        const elTag = this.nativeEl.tagName.toLowerCase();
        if (elTag !== 'img') {
            throw Error(`The "appLogoFromId" directive may only be used on "<img>" elements, but this is a "<${elTag}>" element!`);
        }
    }

    @HostListener('error') onError(): void {
        //404 error on image path, so we instead load this fallback image
        //but if that fallback image ever goes away we don't want to be in a loop here,
        //so we ned to keep track of how many errors we've encountered
        if (this.errCount < 2) {
            this.nativeEl.src = LogoFromIdDirective.fallbackImgUrl;
        }
        this.errCount++;
    }
}

我的問題是:如何測試該指令的@HostListener('error')部分?

我有這個測試,但它失敗了。 我需要做些什么呢?

it('should update the img element src attribute for an invalid image', () => {
    component.bankId = 'foo';
    fixture.detectChanges();
    expect(nativeEl.src).toBe('https://our-website.com/sitelogos/default.svg');
});

錯誤信息:

Expected 'https://our-website.com/sitelogos/foo.jpg' to be 'https://our-website.com/sitelogos/default.svg'.

為了完整性,這是我的指令的整個spec文件

import { LogoFromIdDirective } from './logo-from-id.directive';

import {ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';


@Component({
    template: `<img [appLogoFromId]="theId" />`
})
class TestLogoFromIdOnImgComponent {
    theId: number | string = 5;
}

@Component({
    template: `<div [appLogoFromId]="theId" />`
})
class TestLogoFromIdOnNonImgComponent {
    theId: number | string = 5;
}

describe('Directive: [appLogoFromId]', () => {
    describe('On an `<img>` element', () => {
        let component: TestLogoFromIdOnImgComponent;
        let fixture: ComponentFixture<TestLogoFromIdOnImgComponent>;
        let inputEl: DebugElement;
        let nativeEl: HTMLInputElement;

        beforeEach(() => {
            TestBed.configureTestingModule({
            declarations: [TestLogoFromIdOnImgComponent, LogoFromIdDirective],
            schemas:      [ NO_ERRORS_SCHEMA ]
            });
            fixture = TestBed.createComponent(TestLogoFromIdOnImgComponent);
            component = fixture.componentInstance;
            inputEl = fixture.debugElement.query(By.css('img'));
            nativeEl = inputEl.nativeElement;
        });

        it('should set the img element src attribute for a valid image', () => {
            fixture.detectChanges();
            expect(nativeEl.src).toBe('https://our-website.com/sitelogos/5.jpg');
        });

        it('should update the img element src attribute for a valid image when using a number', () => {
            component.theId = 2852;
            fixture.detectChanges();
            expect(nativeEl.src).toBe('https://our-website.com/sitelogos/2852.jpg');
        });

        it('should update the img element src attribute for a valid image when using a string', () => {
            component.theId = '3278';
            fixture.detectChanges();
            expect(nativeEl.src).toBe('https://our-website.com/sitelogos/3278.jpg');
        });

        it('should update the img element src attribute for an invalid image', () => {
            component.theId = 'foo';
            fixture.detectChanges();
            expect(nativeEl.src).toBe('https://our-website.com/sitelogos/default.svg');
        });
    });

    describe('On a `<div>` element', () => {
        it('should throw an error', () => {
            TestBed.configureTestingModule({
                declarations: [TestLogoFromIdOnNonImgComponent, LogoFromIdDirective],
                schemas:      [ NO_ERRORS_SCHEMA ]
            });
            expect(() => TestBed.createComponent(TestLogoFromIdOnNonImgComponent)).toThrow();
        });
    });
});

這樣的事情應該有效:

inputEl.triggerEventHandler('error', null);
fixture.detectChanges();
expect(nativeEl.src).toBe('https://our-website.com/sitelogos/default.svg');

我終於找到了一個有效的解決方案!

it('should update the img element src attribute for an invalid image', () => {
    const spyError = spyOn(nativeEl, 'onerror' ).and.callThrough();
    component.bankId = 'foo';
    fixture.detectChanges();
    nativeEl.dispatchEvent(new Event('error'));
    expect(spyError).toHaveBeenCalled();
    expect(nativeEl.src).toBe('https://our-website.com/sitelogos/default_bank.svg');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM