3

Is it possible to test the methods in a class that extends LightningElement (e.g. an LWC component) in isolation?

In other words, I think it would be more time effective to simply create an instance of the component class using new MyComponent() and then test the instance methods. In other words, standard plain JavaScript unit tests, rather than DOM-level tests.

It's not that I don't see the value in DOM-level tests, but a lot of logic in LWC components is not DOM related, and it is cumbersome to test it by way of the DOM.

Is it a matter of putting any non-DOM logic in a class that is then imported into the component?

Thanks.

4

As mentioned at the end of the post, your best bet would be to pull out that logic into a separate file and import it into your component as well as directly into a unit test.

A good example of that in the lwc-recpies project would be the mortgage.js library that has it's own tests (no component involved), and is imported into the miscSharedJavascript component for use. The miscSharedJavascript tests can then choose to mock out the mortgage call if they desire.

Also note with the above example the logic pulled out of the component does not need to be in a separate folder and can be a local Javascript file in the component bundle.

1
  • Great. Thanks for you answer.
    – lemming
    Dec 4 '20 at 9:19
2

In one particularly heavy LWC, I pulled out non-DOM logic into a separate helper.js file in the component bundle, which I tested directly with Jest.

This StackExchange answer describes where I put the file and how I folded it into the main component class.

1
  • Thanks Matthew.
    – lemming
    Dec 4 '20 at 9:20

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.