测试图像加载事件Angular 5

时间:2018-10-25 22:18:42

标签: angular jasmine karma-jasmine

我正在与angular 5合作,为我的项目开发一些通用指令,但是我对图像动画指令有疑问;下面的代码是

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

@Directive({
    selector: '[appImageAnimation]'
})
export class ImageAnimationDirective implements OnInit {

    image;
    dimensions;

    constructor(private elem: ElementRef) { }

    ngOnInit(): void {
        this.image = this.elem.nativeElement;
    }

    @HostListener('load')
    onImageLoad() {
        console.log('Image loaded!');
        this.dimensions = {
            width: this.image.naturalWidth,
            height: this.image.naturalHeight
        }
    }
}

我需要测试由图像加载事件触发的onImageLoad方法,我具有以下测试文件

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

import { ImageAnimationDirective } from './image-animation.directive';

@Component({
    template: `
        <div className="cont-test-img">
            <img src="https://picsum.photos/800/450/?random"
                appImageAnimation />
        </div>
    `
})
class ImageTestComponent {
    constructor() {}
}

describe('ImageAnimationDirective', () => {
    let component: ImageTestComponent;
    let fixture: ComponentFixture<ImageTestComponent>;
    let debugElement: DebugElement;
    let directive: ImageAnimationDirective;
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ImageTestComponent, ImageAnimationDirective]
        });
        fixture = TestBed.createComponent(ImageTestComponent);
        component = fixture.componentInstance;
    });

    it('should get dimensions', () => {
        debugElement = fixture.debugElement.query(By.directive(ImageAnimationDirective));
        directive = debugElement.injector.get(ImageAnimationDirective);
        spyOn(directive, 'onImageLoad').and.callThrough();
        expect(directive.dimensions.width).not.toEqual(0);
    });

});

但是该测试失败了,我不知道丢失了什么,或者当加载ImageTestComponent中的图像时执行测试验证的最佳方法是什么

我正在使用 PhantomJS 2.1.1 作为测试浏览器。

谢谢您的帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

我最近正在测试类似的功能,并且首先我决定不从API加载图像,因为http调用比加载静态测试图像更容易出错。

要加载静态图像,首先需要通过修改karma.conf.js并添加

来配置业力(我假设您已经在测试设置中使用)来提供图像
files: [
  { pattern: './<PATH_TO_IMAGE_DIR>/**', watched: false, included:false, nocache:false, served:true }
]

然后通过在上面指定的图像目录之前附加/base来在测试用例中提供图像,当然还要附加图像文件本身。您的规范必须使用茉莉花done函数异步;像这样的东西:

it('should get dimensions', (done) => {
    debugElement = fixture.debugElement.query(By.directive(ImageAnimationDirective));
    directive = debugElement.injector.get(ImageAnimationDirective);
    fixture.detectChanges()

    // wait for a short time to make sure image is requested
    setTimeout(() => {
        expect(directive.dimensions.width).not.toEqual(0);
        done();
    }, 200);
});

如果您决定不提供静态图片,则间隔可能需要更多一些。我没有对此进行测试,但应该可以