4

In a LWC project, I'm setting certain child component style properties from the parent component. I want to test that an element in a child component shows up with those properties when it's rendered, based on a public reactive property that has been set.

The child component:

myComponent.html

<template>
    <div style={headerStyle}>
        Some content...
    </div>
</template>

myComponent.js

import { LightningElement, api } from 'lwc';

export default class MyComponent extends LightningElement {
    @api backgroundColor;

    get headerStyle(){
        return 'background-color:' + this.backgroundColor';';
    }
}

myComponent.test.js

import { createElement } from 'lwc';
import myComponent from 'c/myComponent';

describe('myComponent tests', () => {

    it('renders the background color correctly', () => {

        const element = createElement('c-my-component', {
            is: myComponent
        });

        element.backgroundColor = 'yellow';

        // Add the component to the DOM
        document.body.appendChild(element);

        // Get the div
        let div = element.shadowRoot.querySelector('div');

        // Await async DOM updates
        return Promise.resolve()
            .then(() => {
                // ???
            })

    });

});

1 Answer 1

6

Stumbled across the answer as I was writing up the question.

You can access an element's style properties ( ...drum roll... ) via its style property.

return Promise.resolve()
    .then(() => {
        // This passes
        expect(div.style.backgroundColor).toBe('yellow');
    })

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .