1

i am new to LWC and jest test.So while doing the testing i have got an error.

TypeError: Cannot read properties of null (reading 'style')

js file

@wire(getItemProperty, { iId: '$contactId' })
    GetItemProperty({data}){
        if (data) {
            this.itemValue= data.itemValue;
            this.itemValueColor=data.itemValueColor;
           
           this.template.querySelector('div.itemValueColor').style.setProperty('--itemColor', data.itemValueColor)

}

How to fix this?can someone help?

1
  • Are you able to share the relevant part of the component & the test? Commented Jun 23, 2022 at 21:18

1 Answer 1

1

The problem is not with your test. In your component's code, you have this selector:

this.template.querySelector('div. itemValueColor').style.setProperty('--itemColor', data. itemValueColor)

But there is no element in your markup that matches the div. itemValueColor selector. This explains your error.

As a best practice you should not apply style in this way with LWC because you're not supposed to modify the DOM manually unless your mark the element with the lwc:dom="manual" attribute (see Manipulate the DOM with JavaScript). This only useful in specific cases. In your case, you'll want to write a getter for the style:

<div style={myDynamicStyle}>...</div>
get myDynamicStyle() {
  return `color: ${this.itemValueColor};`;
}
1
  • Updated the example in my answer to use the dynamic itemColor value. I still don't get why you'd want a CSS variable for this? Note that you can't use CSS variables in Jest tests as they are not supported by JSDOM (the virtual browser environment used in tests): github.com/jsdom/jsdom/issues/1895
    – POZ
    Commented Jun 27, 2022 at 12:55

You must log in to answer this question.

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