2

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(() => {
                // ???
            })

    });

});
3

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(layout.style.backgroundColor).toBe('yellow');
            })
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.