0

I have created an LWC in Salesforce and am trying to creat Jest tests for it. I have implemented a div in html file and calling the js function using the onclick event as shown below.

<div class="csa-utility-svg" onclick={handleShowMoreClick} data-id="showMoreButton">
  <label class="card-text-cursor-pointer">{labels.showMore_button} </label>
</div>

How do I test onclick={handleShowMoreClick} through jest?

With both approaches I've tried I get TypeError: Cannot read properties of null (button value is coming as null).

approach 1:

element.shadowRoot.querySelector('div[data-id="showMoreButton"]').dispatchEvent(new CustomEvent('click'));

approach 2:

const showMoreButton = element.shadowRoot.querySelector('div\[data-id="showMoreButton"\]');
expect(showMoreBtn.length).toBeGreaterThan(0);   // real existence check
showMoreBtn\[0\].click();
    await flushPromises();
});
1
  • Welcome to StackOverflow. It would be helpful if you could include a full example jest test you are trying to fix instead of just the event call. Commented Jul 4 at 14:54

1 Answer 1

0

The error TypeError: Cannot read properties of null happens because the element doesn't exist in the DOM when you query for it. You need to append your component to the document body to trigger its render cycle.

Also, querySelector returns a single element (not an array), so you should call .click() on it directly.

Here's the corrected and simplified test flow:

it('should call the handler on click', async () => {
    // 1. Create and append the element to the DOM
    const element = createElement('c-my-component', { is: MyComponent });
    document.body.appendChild(element); // <-- This is the crucial missing step

    // Spy on the handler to check if it's called
    const handlerSpy = jest.spyOn(element, 'handleShowMoreClick');

    // 2. Query for the div
    const showMoreDiv = element.shadowRoot.querySelector('div[data-id="showMoreButton"]');
    expect(showMoreDiv).not.toBeNull(); // A good check to have

    // 3. Click the div and wait for updates
    showMoreDiv.click();
    await flushPromises();

    // 4. Assert the handler was called
    expect(handlerSpy).toHaveBeenCalled();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.