salesforce / lightning-labs

MIT License
3 stars 4 forks source link

Add support for `@wire` mocks #6

Open divmain opened 1 month ago

divmain commented 1 month ago

Currently, there is no ergonomic way for a test author to mock the behavior of an @wire dependency. A mechanism should be built so that the test environment can directly call or modify the state of a mock, on a per-test basis. Once this is in place, an additional layer should be built on top of the first to enable a test to modify the behavior of a wire.

Example component code:

import { LightningElement, api, wire } from "lwc";
import { getRecord } from "lightning/uiRecordApi";
import ACCOUNT_NAME_FIELD from "@salesforce/schema/Account.Name";

export default class Record extends LightningElement {
  @api recordId;

  @wire(getRecord, { recordId: "$recordId", fields: [ACCOUNT_NAME_FIELD] })
  record;
}

Example test code:

import recordApiMock from 'mock{getRecord}:lightning/uiRecordApi';
import mockWire from '@lwc/test-runner';

describe(() => {
  beforeEach(async () => {
    await recordApiMock.reset();
  });

  it('should be possible to mock the wire value', async () => {
    const recordApiWire = await mockWire(recordApiMock, 'getRecord');
    await recordApiWire.setWiredData({
      Name: {
        value: 'foo'
      }
    });
    // Test the component's subsequent behavior.
  });
});
cardoso commented 3 weeks ago

I've been taking a stab at this locally. Should this feature be built upon @salesforce/wire-service-jest-util ?

divmain commented 3 weeks ago

Possibly. That library is largely agnostic to the test runner in which it is invoked, despite the name. We are looking at this one actively right now, although it is proving to be tricky to solve. We may need to revisit some of the baseline mock functionality to really make this ergonomic.

I'd be interested to hear what experiments/thinking you've done on this subject. Would pulling in the Jest util meet your needs? Or are there particular improvements of functionality that you'd like to see?

cardoso commented 1 week ago

@divmain I'm not sure. My priority was to get the wire decorator working and get closer to supporting the components I'm maintaining in prod.

I guess this issue is solved by #21 though.