1

Is it possible to mock uiRecordApi deleteRecord to throw error?

it("should show error toast when delete record method throws error", () => {
        const element = createElement("c-manage", {
            is: manageComp
        });
        
       wireAdapter.emit(mockData);
       const handler = jest.fn();
       element.addEventListener(ShowToastEvent, handler);

        // Act
        document.body.appendChild(element);
  
     
***deleteRecord.error();***
        


        return Promise.resolve()
            .then(() => {
                //expect
            });
    });

1 Answer 1

0

Looking at the stub for uiRecordApi in sfdx-lwc-jest, you can see the only mock is for the resolved value (success):

export const deleteRecord = jest.fn().mockResolvedValue();

Whereas, for example, getRecord provides a wire adapter mock through createLdsTestWireAdapter:

export const getRecord = createLdsTestWireAdapter(jest.fn());

Looking at wire-service-jest-util, you can see the comment on createLdsTestWireAdapter

Returns a wire adapter mock that mimics Lightning Data Service (LDS) adapters behavior, emitted data and error shapes.

It also contains emit() and error() to mock both resolved and rejected scenarios as you're trying to leverage.

You should be able to copy the provided stub from the repo, but tweak it so you can leverage the ability to have an error occur for getRecord

export const deleteRecord = createLdsTestWireAdapter(jest.fn());

Then, update the jest.config.js file to map to your created stub for uiRecordApi module

moduleNameMapper: {
        '^lightning/uiRecordApi$':
            '<rootDir>/force-app/test/jest-mocks/lightning/yourUiRecordApiStub'
    },

Then, you should be able to import your stub of uiRecordApi in your jest test and use deleteRecord.error() within it.

import { deleteRecord } from 'lightning/uiRecordApi';

...
//in your test method
deleteRecord.error();

You must log in to answer this question.

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