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 2,357 times
1
Shashank Vivek
- 15,676
- 8
- 57
- 96
Joe Miller
- 13
- 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
-
@JoeMiller : Take a look at the answer which I have provided – Shashank Vivek Apr 16 '20 at 08:12
3 Answers
2
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
- 15,676
- 8
- 57
- 96
0
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,294
- 3
- 15
- 24
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,506
- 1
- 9
- 7