I am facing an issue with the code below as the test case is failing
//test case
it('should display default image if the image link in people finder result does not 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();
}
});
};
The getImageUrl method is triggered when an image fails to load. It updates the source by replacing the current image's (.jpg) extension and retries loading it with other extensions like .png or .jpeg. If none of the extensions work, the default image is displayed.