2

I am trying to build some shared mocks for common utilities such as the lightning platform resource loader, which I mocked like so:

jest.mock(
    'lightning/platformResourceLoader',
    () => {
        return {
            loadScript() {
                return new Promise((resolve, reject) => {
                    resolve();
                });
            }
        };
    },
    { virtual: true }

);

This is included in my tests, and I know jest support module mocking so I was wondering if the an alternative would be to place under my sfdx-project root a lightning/platformResourceLoader/__mocks__/platformResourceLoader.json file. Is this the right approach to sharing mocks in lwc testing?

1 Answer 1

2

See the Module Imports section under Jest Test Patterns in the LWC Docs.

It's going to be something like this...

Create a custom lightning-platform-resource-loader stub:

force-app\test\jest-mocks\lightning\platformResourceLoader.js

export const loadScript = jest.fn(() => {
    return new Promise((resolve, reject) => {
        resolve();
    });
});

Now customize your Jest configuration:

jest.config.js (this overrides the stub from sfdx-lwc-jest and goes at the root of your project)

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

The stub itself may require tweaking to get it to return exactly the right thing. See my answer on this thread for a working example where I globally mocked another lightning namespace API, lightning/empApi.

6
  • So useful, brilliant. Can I use this pattern to mock also the global.window ?
    – Edmondo
    Commented Dec 21, 2020 at 21:33
  • Haven't tried it, seems worth an attempt. Check this if you haven't already: stackoverflow.com/questions/41885841 Commented Dec 21, 2020 at 21:49
  • also, what about generic test utils? how should they be shared?
    – Edmondo
    Commented Dec 21, 2020 at 21:50
  • I haven't crossed that bridge yet either, and you can probably come to your own conclusion about the proper SFDX directory location for test utils. One option would be to create an LWC bundle with test helpers and use it as described here: developer.salesforce.com/docs/component-library/documentation/…. Or you could put it pretty much anywhere and use a relative import statement to get it. You will also want to read this thread if you haven't yet: stackoverflow.com/questions/50411719 Commented Dec 21, 2020 at 22:01
  • As an example, you can import a helper from another LWC bundle like this: import { helper } from "../../anotherLwc/__tests__/testHelper.js"; Commented Dec 21, 2020 at 22:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .