Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load Google Maps API globally before Jest runs any tests?

Moving to NX, I have migrated my library @bespunky/angular-google-maps from karma + jasmine to jest and my tests are failing.

Many of the tests use native objects (e.g. google.maps.Map or google.maps.Marker). There are existing mock libraries for google maps but they don't cover even 30% of all the Google Maps API.

I intend to implement at least 80% of the native API in my Angular library at some point, which is why neither a mock library nor implementing mocks for every native item I use are viable options as the mocks will quickly become unmaintainable.

For that reason I have chosen to manually download the API file and plant it in my codebase, then simply run it when the test environment initializes. Instead of mocking the entire library, I mock the relevant functions on real objects each time. This worked correctly on karma but fails on jest.

I tried adding the file under setupFiles, setupFilesAfterEnv, globalSetup in my jest.config.js. All alternatives execute the file, but when executed, the following error is thrown:

TypeError: Cannot read property 'maps' of undefined

It's like the google namespace doesn't get loaded. I'm guessing this has something to do with the fact that jest doesn't run on browser and karma did.

I even tried to tell jest to work with DOM simulation, adding the following in my jest.config.js:

module.exports = {
    ...
    testEnvironment: 'jsdom',
    testEnvironmentOptions: { html: `<html><head></head><body></body></html>` }
};

Same result.

like image 477
Shy Agam Avatar asked Oct 18 '25 03:10

Shy Agam


1 Answers

I wrote @googlemaps/jest-mocks which is a partially mocked API for Google Maps JS.

This library is open to pull requests and is easy to patch.

import { initialize } from "@googlemaps/jest-mocks";

beforeEach(() => {
  initialize();
});
like image 119
jpoehnelt Avatar answered Oct 20 '25 15:10

jpoehnelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!