1

I'm building a lightning web component and when adding unit tests, I'm facing the issue that the labels are not rendered in the element when the test is running. What's the best approach to handle this?

4
  • 3
    LWC module name of the label will be returned (eg.c.Greeting_Label). It's possible to mock the label value. Can you please elaborate why would you need to do that? Labels can be translated, or can changed. Because of that the state of your component should not depend on label values. Commented Apr 9, 2019 at 18:48
  • Yes, makes sense, I could validate it against c.Label_Name and leave it as is.
    – pfernandez
    Commented Apr 9, 2019 at 19:37
  • 1
    Personally, I would just check that my element containing label is not.toBeNull();. In LWC import statements you can't reference non-existing label anyway (import iDontExist from '@salesforce/label/c.I_Dont_Exist'; would return an error when deploying). Commented Apr 9, 2019 at 19:53
  • @Michal Varva you should move your comment to an answer so it can be the accepted answer for others with similar issues that end up here. Commented Apr 11, 2019 at 3:49

1 Answer 1

2

You shouldn't test label values. It's not considered as a good practice. Labels can change overtime (or even get translated).

When you reference Custom Label in Lightning Web Component like this:

import helloWorld from '@salesforce/label/c.Hello_World';

export default class MyComponent extends LightningElement {
  helloWorldText = helloWorld;
}
<template>
  <p>{helloWorldText}</p>
</template>

Instead of actual orgs label value, you will get JavaScript module name.

Property helloWorldText will contain c.Hello_World in component test.

const helloWorldText = element.shadowRoot.querySelector('p');
console.log(helloWorldText) // Output: c.Hello_World

@salesforce scoped imports will handle for you the actual existence of referenced object. If you would try to use non-existing Custom Label, you wouldn't be able to deploy (compile) your Component JavaScript file.

If you really wish to change Custom Label value in component test, take a look into lwc-recipes Jest mock examples.

You must log in to answer this question.

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