I have a picture in assets/logo.png
and i wanna check inside the .spec.ts if this picture exists and if not throw error (to be truthy or not). How can i implement something like this ?
Asked
Active
Viewed 3,651 times
2

Shashank Vivek
- 16,888
- 8
- 62
- 104

Joe Miller
- 23
- 1
- 4
-
Does this answer your question? [Angular 2 - Check if image url is valid or broken](https://stackoverflow.com/questions/36429903/angular-2-check-if-image-url-is-valid-or-broken) – AlleXyS Apr 14 '20 at 09:36
-
I use angular 8 and i wanna write unit test - Not checking inside the component.ts file :) – Joe Miller Apr 14 '20 at 09:38
3 Answers
4
You can try below code:
it('should set image logo path as expected', () => {
const ele = fixture.debugElement.nativeElement.querySelectorAll('img');
expect(ele[0]['src']).toContain('logo.png'); // if you dont have `id` in `img` , you need to provide index as `ele[index]`
// OR use
const ele1 = fixture.debugElement.nativeElement.querySelector("#img-id");
expect(ele1['src']).toContain('logo.png');
});
It checks if below image is present in src
attribute. You can be more specific by using .toEqual('assets/logo.png')

Shashank Vivek
- 16,888
- 8
- 62
- 104
2
create a html for image , assign the image path to source and check if the image tag has height and width of the assigned image
it('should set image logo path as expected', () => {
let ele = document.createElement("img");
ele.id = 'eee';
ele.src = this.source;
setTimeout(() => {
expect(ele.height).toBeGreaterThan(0);
expect(ele.width).toBeGreaterThan(0);
}, 5000);
});
if the image path is not correct the width and height of ele
will be 0.

Shlok Nangia
- 2,355
- 3
- 16
- 24
-
This test will always pass. You need to use `doneFn`. I also would recommend to create all elements in a `beforeAll` loop, if possible, so you only have to wait once. – Devpool Nov 17 '22 at 13:18
0
Since I also had to test if 'my-image.png' is not only correctly referred to but also really displayed, I elaborated a bit on Shlok Nangia's answer and came up with the following snippet, which works for me (the else-part is actually not needed):
it('should display my-image.png', () => {
const fixture = TestBed.createComponent(MyComponent);
const compiled = fixture.debugElement.nativeElement;
const imgElement = compiled.querySelector('img.my-class');
if (imgElement) {
const rectangle = imgElement.getBoundingClientRect();
setTimeout(() => {
expect(rectangle.height).toBeGreaterThan(0);
expect(rectangle.width).toBeGreaterThan(0);
}, 10000);
} else {
window.alert('should display my-image.png: failed');
}
});

wbartussek
- 1,850
- 1
- 10
- 8