Search In This Blog

2024-04-24

Jest issue: Fix TypeError getAccountInfo(...).then is not a function (test apex class inside @wire method)

To mock an Apex class
import getAccountInfo from "@salesforce/apex/CustomCtrl.getAccountInfo"

@wire(getRecord,[...])
wireRecord() {
    getAccountInfo(accountId).then(do somethings)
}

Create the jest mock.
jest.mock(
    "@salesforce/apex/CustomCtrl.getAccountInfo",
    () => { return { default: jest.fn(), } }, { virtual: true }
)
 
But mocked apex is called inside of @wire method, then getAccountInfo(...).then is not a function error is happened. Need to fix the mock as below:
jest.mock(
    "@salesforce/apex/CustomCtrl.getAccountInfo",
    () => {
        return {
            default: jest.fn((data) => {
                let mockData;
                if (data.accountId == "0000000000") {
                    mockData = [{
                    "Id": "0011700000xxxxx000",
                    "Name": "test"
                    }];
                } else if (data.accountId == "0000000001") {
                    mockData = [{
                    "Id": "0011700000xxxxx001",
                    "Name": "test1"
                    }];
                }
                // use Promise to mock getAccountInfo(...).then
                return Promise.resolve(mockData);
            }),
        };
    }, { virtual: true }
);