1

I'am using a leaflet map in my LWC and it works perfectly fine. However, when I run the test suite for this component using this command test:unit:coverage, I can see that the test script is stuck at this line var info = L.control();. Do I need to add some mock or any other class related to leaflet to the test suite to cover this part of code? I have attached a part of the code below:

HTML:
<template>
    <div class="leaf-map map-root" lwc:dom="manual"></div>
</template>


JS:
initializeLeaflet() {
    const mapRoot = this.template.querySelector(".map-root");
    this.initializeLeafletWithBoundaries(mapRoot);
}

initializeLeafletWithBoundaries(mapRoot) {
var info = L.control();
  var map = L.map(mapRoot, {
       center: this.center,
       zoom: this.zoom || 16
  });
  this.mapSelected = L.featureGroup([]);

customMap.test.js

describe('Show Leaflet Map', () => {

        afterEach(() => { 
        // The jsdom instance is shared across test cases in a single file so reset the DOM
           while (document.body.firstChild) {
               document.body.removeChild(document.body.firstChild);
           }
        });

        test('displays map1', () => {
        
        const element = createElement('c-custom-map', {
            is: LeafletMap,
        });
        element.center = centerMap;  
        element.zoom = 6;
        element.zipCodeData = mockZipJson;
        element.selectedBoundaries = boundaryData;
        element.radius = mockRadius;
        document.body.appendChild(element);       
        
        expect(element.mapCircle).not.toBeUndefined();      
        });
    });

1 Answer 1

1

Here I see two options:

Option 1 - Assuming leaflet is stored in a static resource, you can force loading the library in test context like this:

let mockScriptSuccess = true;

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.leaflet = require('../../../staticresources/Leaflet/Leaflet');
                        resolve();
                    }
                });
            },
            loadStyle() {
              return Promise.resolve();
          }
        };
    },
    { virtual: true }
);

I took it from this similar example in LWC recipes.

Option 2 - If you don't need the real library imported, you can create a mock, providing a mock implementation for the functions that you're using in your code. For instance:

global.L = { control: jest.fn(), map: jest.fn()}

You must log in to answer this question.

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