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?
1 Answer
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.
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.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).