0

I created a lwc in which I can't mock a getter in the class for unit testing. The class is as follows:

export default class CreateSubscription extends LightningElement {
  isSubAvailable;
  ...
 
  // isSubAvailable conditionally gets set to true/false after an async call when loaded to make it visible or not

  get isAvailable() {
    return this.isSubAvailable;
  }
  ...
}

In the unit test I want to mock the getter 'isAvailable':

describe('c-create-subscription', () => {
    beforeEach(() => {
        jest.spyOn(CreateSubscription, 'isAvailable', 'get').mockReturnValue(true);
    });

    it('bla bla bla', async () => {
      const element = createElement("c-create-subscription", {
        is: CreateSubscription
      });
      document.body.appendChild(element);
      ...
    });
    ...
});

When I run the test I get an error:

isAvailable property does not exist

I can't see whats wrong, any help appreciated

1 Answer 1

0

In your test code, you're trying to mock the isAvailable getter on the CreateSubscription class itself, not on an instance of the class. This won't work because getters are a property of instances of a class, not the class itself.

To fix this, you can create an instance of the CreateSubscription class, and then spy on the isAvailable getter on that instance. Here's an example of how you might do that:

describe('c-create-subscription', () => {
  beforeEach(() => {
    // Create an instance of the CreateSubscription class
    const element = createElement("c-create-subscription", {
      is: CreateSubscription
    });

    // Spy on the isAvailable getter on the instance of the class
    jest.spyOn(element, 'isAvailable', 'get').mockReturnValue(true);

    // Append the element to the DOM so it can be rendered
    document.body.appendChild(element);
  });

  it('bla bla bla', async () => {
    ...
  });
  ...
});

I hope this fixes the issue. Please Let me know if I can help further.

1
  • Thank you for responding, I scoped element to be accessible in the tests but it still returns that it cant find that property, I log out element and it returns HTMLBridgeElement [HTMLElement] {} which explains it but not sure why its not creating the component
    – Corey
    Dec 10, 2022 at 8:58

You must log in to answer this question.

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