1

I'm looking at writing a jest test for the lightning-record-form to test the error handling, The full function should be onError display a Toast event stating the error message to the user

    const handler = jest.fn();
    // Add event listener to catch toast event
    element.addEventListener(ShowToastEvent, handler);

    return Promise.resolve()
        .then(() => {

            const form = element.shadowRoot.querySelector('lightning-record-form');
            expect(form).toBeTruthy();
            form.dispatchEvent(new CustomEvent('error'));
        })
        .then(() => {
                //TODO this needs to check the return of the toast error message
                expect(handler).toHaveBeenCalled();
                expect(handler.mock.calls[0][0].detail.title).toBe('Test');
        });
    });

However expect(handler).toHaveBeenCalled(); is coming back with 'Expected mock function to have been called, but it was not called.'

Does anyone know what i've done wrong with this?

1 Answer 1

1

The toast event is not being fired here most likely because in the Jest unit test the lightning-record-form component is being stubbed out. This happens automatically if you are using the @salesforce/sfdx-lwc-jest test runner.

The stubs for the lightning namespace components are essentially shell implementations to enable testing the logic in your custom components without constantly running into compilation errors when the custom components try to use lightning components that are not available in the unit test environment.

See more info here: https://github.com/salesforce/sfdx-lwc-jest#lightning-namespaced-component-stubs

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .