salesforce / lwc-test

LWC plugins and utilities for testing
MIT License
43 stars 29 forks source link

Update @salesforce/apex/* imports to return jest.fn() #260

Open nwcm opened 1 month ago

nwcm commented 1 month ago

After looking for ways to simplify mocking apex methods in a SFDX project, I found this transformer is applied. However the apex method transforms don't make the imports available within jests.

This change allows for jests import and use apex methods cleanly without having to mock in each test file.

This doesn't apply to wired apex methods which would need createApexTestWireAdapter() from @salesforce/sf

// foo.test.js
import apexMethod from "@salesforce/apex/ApexClass.apexMethod";

describe("c-foo", () => {
  afterEach(() => {
    // resetEnvironment();
  });

  it("Test mock", async () => {
     apexMethod.mockResolvedValue('value');
  }
}

Otherwise any apex method requires

jest.mock(
  "@salesforce/apex/ApexClass.apexMethod",
  () => {
    return {
      default: jest.fn()
    };
  },
  { virtual: true }
);
salesforce-cla[bot] commented 1 month ago

Thanks for the contribution! Before we can merge this, we need @nwcm to sign the Salesforce Inc. Contributor License Agreement.

nolanlawson commented 1 month ago

Thanks for the contribution! Could you clarify: is this a breaking change?

nolanlawson commented 1 month ago

FYI @pozil @Templarian do you have strong opinions about this? Should we just return a jest.fn() so that people can mock directly?

nwcm commented 4 weeks ago

Thanks for the contribution! Could you clarify: is this a breaking change?

Hey @nolanlawson, I don't believe so but can't be 100%. This change did not break any tests across our source which usually directly mock apex in each test file

pozil commented 4 weeks ago

I like the idea of having a mock directly but I have not clue about the potential impact of such a change.