如何编写茉莉花单元测试用例,以便在img标签出现onerror时调用该函数

时间:2019-06-19 14:04:58

标签: angular typescript unit-testing jasmine

下面是我正在使用的代码,但是此测试用例失败了

//test case 
    it('should display default image if the image link in people finder result doesnot exist', fakeAsync(() => {
      debugger
      component.resultsItem = MOCK_RESULTSET.results[9];
      component.resultsItem.imageUrl = "https://domain/gxc3/files/Employee_Images/Test.jpg";
      fixture.detectChanges();
      tick(3000);
      el = fixture.debugElement.queryAll(By.css('.item-person-type'))[0].nativeElement;
      console.log(el);
      let src = el.getAttribute('src');
      expect(src).toBe("assets/img/user-icon.jpg");
    }));

//image tag

 <img class='item-person-type' title="{{resultsItem.text}}"
           [src]="resultsItem.imageUrl ? resultsItem.imageUrl : 'assets/img/user-icon.jpg'"
           (click)="onResultLinkClick(resultsItem)"
           (error)="getImageUrl()" />


//component function

getImageUrl() {
    try {
      var gxcUrl: string = this.resultsItem.imageUrl;
      this.resultsItem.imageUrl = 'assets/img/user-icon.jpg';
      var extensions = this._appSettingsService.appSettings.probableGxcImageExtensions;
      var imageExists = false;
      var probableImageUrls = [];
      extensions.forEach(function (extension) {
        let probableImageUrl = gxcUrl.replace(".jpg", extension);
        probableImageUrls.push(probableImageUrl);
      })
      let observables = probableImageUrls.map(probableImageUrl => this.checkImage(probableImageUrl))
      let source = Observable.forkJoin(observables);
      source.subscribe(response => {
        for (var i = 0; i < response.length; ++i) {
          if (response[i]) {
            imageExists = true;
            this.resultsItem.imageUrl = probableImageUrls[i];
            break;
          }
        }
        if (!imageExists) {
          this.resultsItem.imageUrl = 'assets/img/user-icon.jpg';
        }
      });
    }
    catch (e) {
      this.resultsItem.imageUrl = 'assets/img/user-icon.jpg';
    }
  }

  checkImage(src): Observable<Boolean> {
    return Observable.create((observer: Observer<boolean>) => {
      let img = new Image();
      // img.crossOrigin = 'Anonymous';
      img.src = src;
      if (!img.complete) {
        img.onload = () => {
          observer.next(true);
          observer.complete();
        };
        img.onerror = (err) => {
          observer.next(false);
          observer.complete();
        };
      } else {
        observer.next(true);
        observer.complete();
      }
    });
  };


每当未加载图像时,都会调用getImageUrl方法,并且该方法将替换当前图像(.jpg)源的扩展名,并使用.png或.jpeg等不同的扩展名再次搜索(如果未找到任何图像)的扩展名,然后显示默认图片。

1 个答案:

答案 0 :(得分:0)

测试难以访问的对象的零件的一般解决方案是将其创建转移到工厂,例如,如果您拥有:

class A {
  run() {
    const v = new B(x, y);
    v.doSomeStuff(z, t);
  }
}

您可以执行以下操作:

class A {
  constructor(private bFactory) {}

  run() {
    const v = this.bFactory(x, y);
    v.doSomeStuff(z, t);
  }
}

,然后在测试中可以注入如下内容:

const bMock = { doSomeStuff: jasmine.createSpy('doSomeStuff') }; 
const bFactoryMock = jasmine.createSpy('bFactoryMock').and.return(bMock);
const tested = new A(bFactoryMock);

tested.run():

expect(bFactoryMock).toHaveBeenCalledWith(something, something);
expect(bMock.doSomeStuff).toHaveBeenCalledWith(something, something);