Search code examples
angularkarma-jasminekarma-mochaangular-unit-test

How to get value Angular unit test CSSStyleDeclaration


I try test Angular material mat-expansion-panel open.

So, I test with below code.

describe('Selected first expansion panel', () => {
    beforeEach(() => {
        const header = fixture.debugElement.query(By.css('#panel1 .mat-expansion-panel-header'))!.nativeElement;
        header.click();
        fixture.detectChanges();
    });
    it('should show first expansion panel content', () => {
        const first = fixture.debugElement.query(By.css('#panel1 .mat-expansion-panel-content'))!.nativeElement;
        console.log(first.style);
        expect(first.style.visibility).toEqual('visible');
    });
});

Below console(console.log(first.style)) output is in "it"

CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}
cssText: "visibility: visible;"
length: 1
parentRule: null
cssFloat: ""
0: "visibility"
...
visibility: "visible"
...

But, Failed expect(first.style.visibility).toEqual('visible') with Expected '' to equal 'visible'.

How to get


Solution

  • Try using getComputedStyle on the window object.

    it('should show first expansion panel content', () => {
            const first = fixture.debugElement.query(By.css('#panel1 .mat-expansion-panel-content'))!.nativeElement;
            const styles = getComputedStyle(first);
            console.log(styles); // make sure you get an object
            expect(styles.visibility).toEqual('visible');
        });