Jest error: Cannot find module ‘lightning/alert’ from ‘…/newAccount.test.js’

lightning-web-componentslwc-jest

When I run the test for my LWC I have this error:enter image description here

I read about other issues like that where the solution is to mock the missing function but I cant find something related to action in the repo

my package.json dependencies is :

"@cparra/apexdocs": "2.5.0",
"@salesforce/sfdx-lwc-jest": "1.1.0",
"@salesforce/sfdx-scanner": "2.13.5",
"sfdx-cli": "7.157.0",
"sfdx-git-delta": "5.3.0",
"sfpowerkit": "4.0.3",
"shelljs": "^0.8.4"

Best Answer

You're correct. If the stub is not provided for a standard module in the sfdx-lwc-jest repo, you'll need to create your own. Luckily, the lwc-recipes contains an example specifically for alert.

import { LightningElement, api } from 'lwc';

export default class Alert extends LightningElement {
    static open() {
        throw new Error(
            'The LightningAlert documentation contains examples for mocking .open in Jest'
        );
    }
    @api label;
    @api message;
    @api theme;
    @api variant;
}

You'll also want to update your jest.config.js file which will point the import to your stub.

const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
    ...jestConfig,
    moduleNameMapper: {
        ...
        '^lightning/alert$':
            '<rootDir>/force-app/test/jest-mocks/lightning/alert',
        ...
    },
    testTimeout: 10000
};

The above pattern is covered in Jest Test Patterns and Mock Dependencies under Module Imports