Shashank Vivek
Shashank Vivek

Reputation: 17514

Testing background-image of a css class using Angular Karma

I have a div, for which I have created a a class lets say .open-banner which is something like :

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

with css classes as :

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

In my spec file, I am trying to access the url of image and test if it loads proper image using:

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

But it's coming as empty. What am I doing wrong ?

Actually, doing console.log(ele.style) gives all empty values as below:

LOG: 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: '', ......

Upvotes: 0

Views: 1637

Answers (1)

user700284
user700284

Reputation: 13620

When you try to access ele.style, it only gives the styles that are defined on the element through the style attribute. To get the styles defined through classes and all, you can make use of the getComputedStyle method - https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

So this should get you the style value you are looking for

console.log(getComputedStyle(ele).backgroundImage);

Upvotes: 3

Related Questions