Reputation: 23
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 ?
Upvotes: 2
Views: 4232
Reputation: 2018
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');
}
});
Upvotes: 0
Reputation: 2377
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.
Upvotes: 2
Reputation: 17514
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')
Upvotes: 4