[SalesForce] LWC Error: Cannot set property ‘textContent’ of null

I have an lwc class with the following HTML:

<template if:true={showModalButton}>
    <lightning-button class="right-col-button" variant="base" label={modalButtonLabel} onclick={openModal}></lightning-button>
</template>

below is the JS related to this:

    export default class customlwccomponent extends LightningElement {
        @api recordId;
        fileName = null;
        uploadedFileId = null;
        showModalButton = false;
        modalButtonLabel = '';
        showFileName = false;
        uploadedDocId = null;
        errorMessage = null;
        uploadedFileIds = [];
        isModalOpen = false;

        updateDisplayText() {
            console.log('updateDisplayText');
            if (this.uploadedFileIds.length === 0) {
                this.showModalButton = false;
                this.showFileName = false;
                this.fileName = null;
                this.uploadedFileId = null;
            } else if (this.uploadedFileIds.length === 1) {
                this.showModalButton = false;
                this.showFileName = true;
                this.fileName = this.uploadedFileIds[0].Title;
                this.uploadedFileId = this.uploadedFileIds[0].Id;
            } else {
                this.showModalButton = true;
                this.showFileName = false;
            }
            console.log('uploadedFileIds.length='+this.uploadedFileIds.length);
            this.modalButtonLabel = this.uploadedFileIds.length.toString() + ' files uploaded';
        }
    
        openModal() {
            this.isModalOpen = true;
        }
        closeModal() {
            this.isModalOpen = false;
        }

below is the jest test code that I have written to cover the above component:

     test("Validate modal popup", () => {
        const element = createElement("c-custom-component", {
          is: customlwccomponent
        });
        element.contentDocs = data;
        document.body.appendChild(element);
    
        const text = element.shadowRoot.querySelector("lightning-button");
        expect(text.textContent).toBe("1 files uploaded ");
      });     
     }

Now when I run the above test, I am seeing the following error:

Cannot set property 'textContent' of null

Can anyone please let me know how to resolve this error

Best Answer

Your text variable (the lightning-button) is null because it's absent from the DOM.

It's absent from the DOM because it's inside the <template if:true={showModalButton}> element. showModalButton, which controls that template element, is going to evaluate to false the way your code looks currently.

As far as I can see, the only way for showModalButton to get set to true is for updateDisplayText() to get invoked somehow. But nothing is invoking that function.

Related Topic