Having issue with jest test for Lightning Quick action and CloseActionScreenEvent

lightning-web-componentslwc-jest

We have a lightning web component which uses lightning quick action tag and this line in js file:

import { CloseActionScreenEvent } from "lightning/actions";

And when I run jest test I have got the error. So I have gone through the existing question and have updated my package.json file into:

"@salesforce/sfdx-lwc-jest": "^1.0.0",

And I have also updated the sfdx-project version to 53. The Cannot find module 'lightning/quickActionPanel' error is gone. But I am still seeing the below error:

Cannot find module 'lightning/actions'

In CloseActionScreenEvent js file line. How should we walkaround this issue?

Best Answer

In the sfdx-lwc-jest repository, you can see what lightning-stubs they've created.

QuickActionPanel has an appropriate stub which is why updating to the a later version (that added this stub) solved your initial issue, but you'll notice there is none for lightning/actions. As a result, you have to create one yourself.

There's actually an example of creating your own jest-mocks in the lwc-recipes that allows them to create a jest test for the editRecordScreen component.

/**
 * Close Screen Action Event base class
 */
export const CloseScreenEventName = 'lightning__actionsclosescreen';

export class CloseActionScreenEvent extends CustomEvent {
    constructor() {
        super(CloseScreenEventName, { bubbles: false, composed: false });
    }
}

Then, in your jest test

import { CloseScreenEventName } from 'lightning/actions';