Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Angular 8单元测试检查给定路径中是否存在图像?_Javascript_Angular_Typescript_Unit Testing_Karma Jasmine - Fatal编程技术网

Javascript 如何使用Angular 8单元测试检查给定路径中是否存在图像?

Javascript 如何使用Angular 8单元测试检查给定路径中是否存在图像?,javascript,angular,typescript,unit-testing,karma-jasmine,Javascript,Angular,Typescript,Unit Testing,Karma Jasmine,我在assets/logo.png中有一张图片,我想在.spec.ts中检查这张图片是否存在,如果没有抛出错误(真实与否)。如何实现这样的功能?您可以尝试以下代码: it('should set image logo path as expected', () => { const ele = fixture.debugElement.nativeElement.querySelectorAll('img'); expect(ele[0]['src'

我在
assets/logo.png
中有一张图片,我想在.spec.ts中检查这张图片是否存在,如果没有抛出错误(真实与否)。如何实现这样的功能?

您可以尝试以下代码:

    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');
    });

它检查
src
属性中是否存在下面的图像。您可以使用
.toEqual('assets/logo.png')

为图像创建html,将图像路径指定给源,并检查图像标记是否具有指定图像的高度和宽度

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);
 });

如果图像路径不正确,
ele
的宽度和高度将为0。

因为我还必须测试“my image.png”是否不仅正确引用,而且是否真正显示,我详细阐述了Shlok Nangia的答案,并提出了以下代码片段,这对我来说很有用(实际上不需要其他部分):


这回答了你的问题吗?我使用angular 8,我想编写单元测试,而不是检查component.ts文件:)@JoeMiller:看看我提供的答案
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');
    }
});