使用Angular Karma测试css类的背景图像

问题描述 投票:0回答:1

我有一个div,为此我创建了一个类,让我们说.open-banner,它是这样的:

<div class="banner-section open-banner"
     [ngClass]="{'banner-closed' : !isOpen}">
</div>

使用css类:

.open-banner {
    background-image: url("/assets/images/image1.jpg");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}


.banner-closed {
    background-image: url("/assets/images/image2.jpg");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

在我的spec文件中,我试图访问图像的URL并测试它是否使用以下方法加载正确的图像:

fit('should set banner background',()=>{
    component.isOpen = true;
    fixture.detectChanges();
    const ele = fixture.debugElement.query(By.css('.open-banner')).nativeElement;
    console.log(ele.style.backgroundImage)
});

但它变得空洞。我究竟做错了什么 ?

实际上,做console.log(ele.style)会给出所有空值,如下所示:

日志:CSSStyleDeclaration {alignContent:'',alignItems:'',alignSelf:'',alignmentBaseline:'',all:'',animation:'',animationDelay:'',animationDirection:'',animationDuration:'',animationFillMode :'',animationIterationCount:'',animationName:'',animationPlayState:'',animationTimingFunction:'',backfaceVisibility:'',background:'',backgroundAttachment:'',backgroundBlendMode:'',backgroundClip:'',backgroundColor :'',backgroundImage:'',backgroundOrigin:'',backgroundPosition:'',backgroundPositionX:'',backgroundPositionY:'',backgroundRepeat:'',backgroundRepeatX:'',backgroundRepeatY:'',backgroundSize:'',baselineShift :'',blockSize:'',border:'',borderBlockEnd:'',borderBlockEndColor:'',borderBlockEndStyle:'',borderBlockEndWidth:'',borderBlockStart:'',borderBlockStartColor:'',borderBlockStartStyle:'',. .....

angular unit-testing karma-jasmine karma-runner
1个回答
1
投票

当您尝试访问ele.style时,它仅通过style属性提供在元素上定义的样式。要获得通过类和所有定义的样式,您可以使用getComputedStyle方法 - https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

所以这应该为您提供您正在寻找的风格价值

console.log(getComputedStyle(ele).backgroundImage);
© www.soinside.com 2019 - 2024. All rights reserved.