5

I have an LWC that loads two external js libraries:

import { api, LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import LightningUtil from 'c/lightningUtil';
// apex methods
import getCredentials from '@salesforce/apex/ALKMapController2.getCredentials';
// static resources
import ALK1 from '@salesforce/resourceUrl/ALK1';
import ALK2 from '@salesforce/resourceUrl/ALK2';
// custom labels
import Label_Map from '@salesforce/label/c.Map';

...

    connectedCallback() {

    loadScript(this, ALK1)
    .then(() => {
        loadScript(this, ALK2)
        .then(() => {
            this.getAPICredentials();
        })
        .catch(error => {
            LightningUtil.logError(this, error, false);
        });        
    })
    .catch(error => {
        LightningUtil.logError(this, error, false);
    });    
}

Question: How do you mock the loadScript calls in JEST?

Thanks!

1 Answer 1

6

Here an example of custom mock of loadScript for loading moment.js lib, taken from lwc-recipes

jest.mock(
    'lightning/platformResourceLoader',
    () => {
        return {
            loadScript() {
                return new Promise((resolve, reject) => {
                    // If the variable is false we're simulating an error when loading
                    // the script resource.
                    if (!mockScriptSuccess) {
                        reject('Could not load script');
                    } else {
                        global.moment = require('../../../staticresources/moment');
                        resolve();
                    }
                });
            }
        };
    },
    { virtual: true }
);

Note that '../../../staticresources/moment' is a local relative path to the lib mock because Jest Tests run locally.

In your case the code might looks like:

jest.mock(
    'lightning/platformResourceLoader',
    () => {
        return {
            loadScript() {
                return new Promise((resolve, reject) => {
                    // Sequentially loads the first and the second mocks only once if they weren't loaded previously
                    global.ALK1 ??= require('../../../staticresources/ALKMOCK1');
                    global.ALK2 ??= require('../../../staticresources/ALKMOCK2');
                    resolve();
                });
            }
        };
    },
    { virtual: true }
);
1
  • Thanks, Oleh! I will give that a try.
    – Dave C
    Mar 26, 2021 at 12:59

You must log in to answer this question.

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