Shy Agam
Shy Agam

Reputation: 1415

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.

Upvotes: 4

Views: 2298

Answers (1)

Justin Poehnelt
Justin Poehnelt

Reputation: 3469

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();
});

Upvotes: 3

Related Questions