You need to sign in to do that
Don't have an account?
Greg Coogan
Testing a Property in a Lightning Web Component
I've built a Lightning Web Component and need to write a Jest unit test class for it. A part of the component only renders when a tracked property, called it "showDesktopView" is true. The default value is false. For a Jest test case to pass, the section needs to render. Therefore, I need a method that will result in "showDesktopView" being set to true. It is set to true when the UI theme isn't mobile.
The property:
I've tried the below appproaches of setting the property, but they don't work.
Does anyone know how to correctly set this property from a Jest unit test?
The property:
@track showDesktopView = false;
I've tried the below appproaches of setting the property, but they don't work.
const element = createElement('c-test', { is: testLWC }); element.showDesktopView = "true"; //Trial 1 element.showDesktopView = true; //Trial 2 document.body.setAttribute('showDesktopView','true'); //Trial 3 document.body.appendChild(element); return Promise.resolve().then(() => { // My promise code });They don't seem to work since my Promise fails. I know my code in the Promise works because if I set the property "showDesktopView" to a default value of true, then it passes.
Does anyone know how to correctly set this property from a Jest unit test?
Test a Property Change
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.unit_testing_using_jest_patterns
That is the same documentation I've been using. That is basically my Trial 2 approach, but document.body.appendChild(element) is before the element assignment. I tried it in that order as well, but it didn't work. The error I get back is the querySelector doesn't find the element. However, when I default the value in my code to true for showDesktopView (which I cannot leave it like that), the query selector does find the "Name" element it is looking for.
This is a closer representation of my code following what you suggested, but doens't work:
The error I get back is "TypeError: Cannot read property 'textContent' of null" which is recieved when the querySelector doesn't find the rendered element. Again, the test case does pass if I default the showDesktopView to true.
const content = element.shadowRoot.querySelector('.myclass');
element.shadowRoot is not the common this.shadowRoot as you can find in the mozilla documentation but it is equivalent to this.template for LWC.
You can try in your code (not the jest test) if const content = this.template.querySelector('.myclass'); is resolved.
In my jest test, the element.shadowroot.querySelector does work if I default showDesktopView to true. The test case passes, it finds the name value.
I also found this in my jest test, if I use element.querySelector when default showDesktopView is true, the case fails.