2

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";

3

Out 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

  1. Create a folder in your test/jestmocks in your project root. Usually under force-app if force-app is your default directory.

  2. 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

  3. Now create a file with name formFactor.js and use the below code in the file

    export const formFactorPropertyName;
    
  4. 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'
      }
    

    };

  5. 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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.