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' })
        if (data) {
            this.itemValue= data.itemValue;
           this.template.querySelector('div.itemValueColor').style.setProperty('--itemColor', data.itemValueColor)


How to fix this?can someone help?

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

1 Answer 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};`;
  • 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
    Jun 27 at 12:55

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.