最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How check with Angular 8 unit test if image exists in given path? - Stack Overflow

programmeradmin3浏览0评论

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 ?

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 ?

Share Improve this question edited Apr 16, 2020 at 8:12 Shashank Vivek 17.5k9 gold badges69 silver badges110 bronze badges asked Apr 14, 2020 at 9:34 Joe MillerJoe Miller 231 silver badge4 bronze badges 2
  • Does this answer your question? Angular 2 - Check if image url is valid or broken – AlleXyS Commented Apr 14, 2020 at 9:36
  • I use angular 8 and i wanna write unit test - Not checking inside the ponent.ts file :) – Joe Miller Commented Apr 14, 2020 at 9:38
Add a ment  | 

3 Answers 3

Reset to default 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')

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.

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 piled = fixture.debugElement.nativeElement;
    const imgElement = piled.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');
    }
});
发布评论

评论列表(0)

  1. 暂无评论