salesforce / sfdx-lwc-jest

Run Jest against LWC components in SFDX workspace environment
MIT License
165 stars 82 forks source link

Jest Test failing because it can't resolve stub #248

Closed AllanOricil closed 3 years ago

AllanOricil commented 3 years ago

Description

I have an LWC that is used on a Quick Action and I can't test it because of this error

image

I followed exactly your example for testing LWC used in a Quick Action and it did not work. These are my dev dependencies:

"devDependencies": {
        "@prettier/plugin-xml": "^0.12.0",
        "@sa11y/jest": "^0.4.3",
        "@salesforce/eslint-config-lwc": "^0.7.0",
        "@salesforce/eslint-plugin-aura": "^1.4.0",
        "@salesforce/sfdx-lwc-jest": "^1.0.1",
        "eslint": "^7.6.0",
        "eslint-config-prettier": "^6.11.0",
        "husky": "^4.2.1",
        "lint-staged": "^10.0.7",
        "prettier": "2.3.2",
        "prettier-plugin-apex": "1.10.0",
        "xml-js": "^1.6.11",
        "fs-extra": "^10.0.0",
        "simple-git": "^2.45.1"
    },

and this is my Node Version: 14.17.3

Steps to Reproduce

1 - Create a LWC to use in a Quick Action 2 - Create a Jest test following this recipe https://github.com/trailheadapps/lwc-recipes/blob/main/force-app/main/default/lwc/editRecordScreenAction/__tests__/editRecordScreenAction.test.js 3 - Run the test and verify you get the same error I showed in the image

Expected Results

Test should run and the stub should be resolved

Actual Results

Test can't start because it cant find a stub

Version

Possible Solution

no solution

Additional context/Screenshots

image

AllanOricil commented 3 years ago

So I finally understood what I was missing. To solve this problem you have to add this folder to your project

https://github.com/trailheadapps/lwc-recipes/tree/main/force-app/test/jest-mocks

it contains all the mocks you will need.

Then, in the root of your project, you have to add these configs on your jest.config.js file. This will tell jest where to look for the mocks :D

moduleNameMapper: {
        '^@salesforce/apex$': '<rootDir>/salesforce_sfdx/test/jest-mocks/apex',
        '^@salesforce/schema$': '<rootDir>/salesforce_sfdx/test/jest-mocks/schema',
        '^lightning/navigation$':
            '<rootDir>/salesforce_sfdx/test/jest-mocks/lightning/navigation',
        '^lightning/platformShowToastEvent$':
            '<rootDir>/salesforce_sfdx/test/jest-mocks/lightning/platformShowToastEvent',
        '^lightning/uiRecordApi$':
            '<rootDir>/salesforce_sfdx/test/jest-mocks/lightning/uiRecordApi',
        '^lightning/messageService$':
            '<rootDir>/salesforce_sfdx/test/jest-mocks/lightning/messageService',
        '^lightning/actions$':
            '<rootDir>/salesforce_sfdx/test/jest-mocks/lightning/actions'
    },

Obs: dont forget that the location of the mocks will be different on each project. Mine is on a folder called "salesforce_sfdx"