1

I am facing an issue while trying to develop some LWC Jest tests and wondering if I can get some help on it.

Starting off with some context: I have an LWC component consisting of the following:

HTML

<template>
  Example text!
      <template lwc:if={isErrorState}>
          <c-error-component error-message={error}></c-error-component>
      </template>
</template>

JS

export default class MyComponent extends LightningElement {
  @api
  error = null;


  get isErrorState() {
    return this.error;
  }
}

Regarding the Jest tests, this is what I have as a base:

import { createElement } from "lwc";

import { resetDOM, flush } from "c/utilsTest";
import myComponent from "c/myComponent";

let element;

describe("c-my-component", () => {
  beforeEach(async () => {
    element = createElement("c-my-component", {
      is: myComponent,
    });
    document.body.appendChild(element);
  });
      //Individual tests here
});

And now for the fun part, my individual tests!

This one where I specifically set the value of error, works as expected, meaning that the shadowDom now contains the conditionally rendered component.

it("The error-component should be displayed in error state.", async () => {
    let errorComponent =
      element.shadowRoot.querySelector("c-error-component");
    expect(errorComponent).toBeNull();

    element.error = "TEST_ERROR";

  return Promise.resolve().then(() => {

    errorComponent =
      element.shadowRoot.querySelector("c-error-component");
    expect(errorComponent).not.toBeNull();
      });
  });
 

However, applying jest.spyOn (as seen suggested on LWC jest test on conditional element and Cannot mock an lwc getter with Jest) to mock the getter does not seem to reflect any changes on shadowDom, even though the property returned by the getter returns the expected value. So it seems like the getter is not called but only mocked.

  it("The error-component should be displayed in error state.", async () => {
    let errorComponent =
      element.shadowRoot.querySelector("c-error-component");
    expect(errorComponent).toBeNull();

    jest.spyOn(element, "isErrorState", "get").mockReturnValue(true);


  return Promise.resolve().then(() => {
    console.log(element.isErrorState); // This returns true;
    const errorComponent =
      element.shadowRoot.querySelector("c-error-component");
    expect(errorComponent).not.toBeNull();
    });
});

I guess ultimately my question would be: if I want to stick with mocking the getter and not the variable it returns, is there any way to force the re-rendering of the component?

Thank you in advance for the help!

0

You must log in to answer this question.

Browse other questions tagged .