I am getting this error: Cannot find module '@salesforce/client/formFactor' when I run jest test, But it works in a scratch org.
import { LightningElement, api } from "lwc";
import formFactorPropertyName from "@salesforce/client/formFactor";
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityOut of box sfdx-lwc-jest does not provide a mock stub for @salesforce/client/formFactor and hence you are getting the error.
The easiest and simplest way is to implement a jest mock. If you are looking to just do this for one component and not globally use the below approach in your .test.js
import formFactorPropertyName from '@salesforce/client/formFactor';
jest.mock(
'@salesforce/client/formFactor',
() => {
return { default: 'Large' };
},
{ virtual: true }
);
// rest of code
expect(formFactorPropertyName).toBe('Large');
If you have this in multiple components then you can follow below
You can create your own stub for this module in jest using moduleNameMapper property in the jest.config.js file.
Below are the steps you will need to follow
Create a folder in your test/jestmocks
in your project root. Usually under force-app if force-app is your default directory.
Create a folder path that is a similar name to the module you want to mock. In your case you will create a folder named @salesforce/client
under test/jestmocks
Now create a file with name formFactor.js
and use the below code in the file
export const formFactorPropertyName;
Configure your jest.config.js as below
const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');
module.exports = {
...jestConfig,
moduleNameMapper: {
'^@salesforce/client/formFactor$':
'<rootDir>/force-app/test/jest-mocks/@salesforce/client/formFactor.js'
}
};
Import the module in your <component>.test.js
as below
import formFactorPropertyName from '@salesforce/client/formFactor
;
Assign the mock value using in your test
formFactorPropertyName = 'Large'