Skip to main content
3 of 6
added 868 characters in body
Kris Goncalves
  • 22.8k
  • 8
  • 35
  • 72

Two things:

  1. You probably should handle the scenario where there's nothing to focus on in your component. That would seem reasonable considering you're hiding that element if there's no userData. If the element is not found, you shouldn't be doing a focus. That may happen in real-world usage when the wire returns an error.
  2. If you do the above, then the jest test becomes easier as well as your component can now handle not receiving certain info. You'll just want to set your api field before creating the component/element.

For #2 above, a public property (patient) would be getting set when created (<c-mycomponent patient={passedInData}...).

As such, to mimic the real-world scenario - you'd want to set your api value before creating the component/element in your jest test.

element.patient = PATIENT_MOCK;
document.body.appendChild(element);
//mock wire and wait for DOM updates to assert
getUserInfo.emit(USER_MOCK);
return Promise.resolve().then(() => {});

If you don't want to update your component to handle the scenario where it might not find the element to focus on, you can still jest test this. However, you want to provide a resolved value for the wire on its initial run (when the element is appended) versus emitting a response afterward it has already rendered once and failed (since no userData existed). You'd want to remove this:

jest.mock(
  "@salesforce/apex/OnboardingControllers.getUserInfo",
  () => {
    const { createApexTestWireAdapter } = require("@salesforce/sfdx-lwc-jest");
    return {
      default: createApexTestWireAdapter(jest.fn())
    };
  },
  { virtual: true }
);

You're removing the above as you're not looking to leverage emit() or error(). Instead, you'll

And instead, provide a mock for the resolved value of the imported wire module. This is the data it'll return when the promise/wire is successful/resolved - when data is returned.

getUserInfo.mockResolvedValue(USER_MOCK);
element.patient = PATIENT_MOCK;
document.body.appendChild(element);
...

Kris Goncalves
  • 22.8k
  • 8
  • 35
  • 72