@googlemaps/jest-mocks

中文文档
2.22.8发布于 2026/02/11Apache-2.0TypeScriptCommonJS零依赖近 30 天下载 69.8万

[npm][npm-pkg] Release Stable [![Tests/Build](https://github.com/go

原始使用文档
文档目录11 节
  1. Description
  2. Requirements
  3. Installation
  4. Usage
  5. Testing Events
  6. Extending Mocks
  7. Mocking Services
  8. Cleaning up mocks
  9. Contributing
  10. Terms of Service
  11. Support

npm Release Stable Tests/Build

codecov semantic-release solidarity

Contributors License StackOverflow Discord

Jest Mocks for Google Maps

Description

Jest mocks for Google Maps in TypeScript.

Note: If you find a missing mock, please file an issue.

Requirements

Installation

Available via NPM as the package @googlemaps/jest-mocks

npm i @googlemaps/jest-mocks

Usage

These mocks need the tests to run in a browser-like environment (for example jest-environment-jsdom).

Before running the tests, you have to call the exported initialize function to set up the global namespaces of the mocked Google Maps API:

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

beforeEach(() => {
  initialize();
});

You can then run the test-code that makes use of the Maps API almost as normal. "Almost" is referring to the fact that the objects are all non-functional and some things you can do with the real maps API cannot be done with the mocks library.

We also export the mockInstances object and mocked constructors of all classes (e.g. Map or Marker) that can be used to retrieve, inspect and configure the mocks.

import { initialize, Map, Marker, mockInstances } from "@googlemaps/jest-mocks";

// this represents your code being tested
function codeUnderTest() {
  const map = new google.maps.Map(null);
  const markerOne = new google.maps.Marker();
  const markerTwo = new google.maps.Marker();

  map.setHeading(8);
  markerOne.setMap(map);
  markerTwo.setLabel("My marker");
}

beforeEach(() => {
  initialize();
});

test("my test", () => {
  codeUnderTest();

  // mockInstances stores the lists of all maps-objects created since
  // `initialize` was called, organized by constructor.
  const mapMocks = mockInstances.get(Map);
  const markerMocks = mockInstances.get(Marker);

  expect(mapMocks).toHaveLength(1);
  expect(markerMocks).toHaveLength(2);
  expect(mapMocks[0].setHeading).toHaveBeenCalledWith(8);
  expect(markerMocks[0].setMap).toHaveBeenCalledTimes(1);
  expect(markerMocks[1].setLabel).toHaveBeenCalledWith("My marker");

  // note that this will not work (`map.setHeading(8)` will not update any
  // internal state of the map):
  expect(mapMocks[0].getHeading()).toBe(8);
});

Testing Events

To test code that uses events dispatched by Maps API objects, you can follow a pattern like this:

import { mockInstances, Map } from "./registry";

let eventTriggered = false;

function codeUnderTest() {
  const map = new google.maps.Map(null);
  const listener = map.addListener("bounds_changed", () => {
    // whatever happens here should be observeable in some way, for the
    // sake of this example, we just set a global variable:
    eventTriggered = true;
  });
}

test("testing events", () => {
  // run the code under test, which will register an event-listener
  codeUnderTest();

  // since `map.addListener` doesn't actually do anything, we'll have to
  // retrieve the event-handler function and trigger the event ourselves
  const map: google.maps.Map = mockInstances.get(Map);
  const addListener: jest.MockedFunction<typeof map.addListener> =
    map.addListener;

  expect(addListener).toHaveBeenCalledTimes(1);

  const [eventType, listener] = addListener.mock.lastCall;

  // call the listener function (for mouse-events you'd have to create the
  // event-object here as well)
  listener();

  // assert that whatever the effect of your code receiving the event happened
  expect(eventTriggered).toBe(true);
});

Extending Mocks

There are situations where you need some more functionality from the mocks than what is provided by this library. In these cases, you can extend the existing mocks.

For example, if you want to observe the creation of a Map instance to validate constructor-arguments, you can add a spy function like this:

let createMapSpy: jest.Mock<
  void,
  ConstructorParameters<typeof google.maps.Map>
>;

beforeEach(() => {
  initialize();

  createMapSpy = jest.fn();

  // overwrite the mock implementation with an anonymous class
  google.maps.Map = class extends google.maps.Map {
    constructor(...args: ConstructorParameters<typeof google.maps.Map>) {
      createMapSpy(...args);
      super(...args);
    }
  };
});

test("map constructor", () => {
  const mapOptions = { mapId: "abcd" };
  const map = new google.maps.Map(null, mapOptions);

  expect(createMapSpy).toHaveBeenCalledWith(null, mapOptions);
});

So essentially, you can overwrite the classes in the global google.maps namespace with your own classes extending the existing ones. The initialize function will always restore them to their initial state.

Mocking Services

If your code is interacting with services provided by the Maps API, you can control the results that will be returned when calling the methods of the service. First you need to get the service instance that was created by your code using the mockInstances registry:

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

beforeEach(() => {
  initialize();
});

test("...", () => {
  // [... do something that creates a google.maps.AutocompleteService instance]

  const [serviceMock] = mockInstances.get(AutocompleteService);
  expect(serviceMock.getPlacePredictions).toHaveBeenCalled();
});

Note that the imported AutocompleteService and google.maps.places.AutocompleteService are the same object. The only difference is that the former one is known to be the mocked version (so you can access the mock-interface without type-errors when writing tests in TS.

Since the mocked methods are created in the constructor of the mocked AutocompleteService, we can't overwrite the behavior of the methods before the constructor has been called.

If the creation of the AutocompleteService is separated from it's usage, this is relatively easy:

// assuming your class under test looks like this:
class MyAutocomplete {
  constructor() {
    this.service = new google.maps.places.AutocompleteService();
  }

  async update() {
    const res = await this.service.getPlacePredictions();
  }
}

// configure the mocks after the constructor has been called:
test("...", async () => {
  const subject = new MyAutocomplete();

  const [serviceMock] = mockInstances.get(AutocompleteService);
  serviceMock.getPlacePredictions.mockImplementation(() => {
    return {
      // whatever you want the return-value to be
    };
  });

  // now call the method under test
  await subject.update();

  // validate the outcome
});

The same applies if you can somehow separate the creation of the service-object from its usage, for example, by monkey-patching it in the tests:

test("...", async () => {
  const subject = new MyAutocomplete();

  // this is assuming that `subject.update()` will internally call a method
  // `this.createAutocompleteService()` when called.
  subject.createAutocompleteService = jest.fn(() => {
    const svc = new AutocompleteService();

    // configure mocked methods as above

    return svc;
  });

  await subject.update();
});

Both of these solutions are probably more of an antipattern, since they expose implementation details (like the service property or the createAutocompleteService method) to the test, making it harder to change the implementation without updating the test.

The recommended way is to achieve this is to replace the AutocompleteService class entirely to get full control over its behavior in your tests:

const getPlacePredictionsMock = jest.fn();
class MockAutocompleteService extends AutocompleteService {
  constructor() {
    super();

    this.getPlacePredictions = getPlacePredictionsMock;
  }
}

test("...", () => {
  google.maps.places.AutocompleteService = MockAutocompleteService;
  getPlacePredictions.mockImplementation(() => {
      return { ... };
  });

  // run your test
});

Cleaning up mocks

Whenever initialize() is called, the captured mocks are automatically cleaned. Using any of Jest's methods, you can clean the mock instances at any time:

import { initialize, Map, Marker, mockInstances } from "@googlemaps/jest-mocks";

beforeAll(() => {
  initialize();
});

// Clear all mocks
beforeEach(() => {
  mockInstances.clearAll();
});

// Clear specific mocks
beforeEach(() => {
  mockInstances.clear(Map, Marker);
});

Contributing

Contributions are welcome and encouraged! If you'd like to contribute, send us a pull request and refer to our code of conduct and contributing guide.

Terms of Service

This library uses Google Maps Platform services. Use of Google Maps Platform services through this library is subject to the Google Maps Platform Terms of Service.

This library is not a Google Maps Platform Core Service. Therefore, the Google Maps Platform Terms of Service (e.g. Technical Support Services, Service Level Agreements, and Deprecation Policy) do not apply to the code in this library.

Support

This library is offered via an open source license. It is not governed by the Google Maps Platform Support [Technical Support Services Guidelines, the SLA, or the Deprecation Policy. However, any Google Maps Platform services used by the library remain subject to the Google Maps Platform Terms of Service.

This library adheres to semantic versioning to indicate when backwards-incompatible changes are introduced. Accordingly, while the library is in version 0.x, backwards-incompatible changes may be introduced at any time.

If you find a bug, or have a feature request, please file an issue on GitHub. If you would like to get answers to technical questions from other Google Maps Platform developers, ask through one of our developer community channels. If you'd like to contribute, please check the contributing guide.

You can also discuss this library on our Discord server.

版本与发布记录

@googlemaps/jest-mocks 共发布 72 个版本,首次发布于 2019/11/08;过去 12 个月发布了 1 个版本。

版本发布日期距今
2.22.8latest2026/02/119 个月前
2.22.62025/02/141.8 年前
2.21.42023/12/012 年前
2.21.32023/12/012 年前
2.21.22023/11/302 年前
2.20.22023/10/173 年前

关于 @googlemaps/jest-mocks 的常见问题

@googlemaps/jest-mocks 是什么?

[][npm-pkg] [![Tests/Build](https://github.com/go

如何安装 @googlemaps/jest-mocks?

在项目目录运行 npm install @googlemaps/jest-mocks,或使用 pnpm add / yarn add / bun add。

@googlemaps/jest-mocks 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@googlemaps/jest-mocks 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@googlemaps/jest-mocks 可以商用吗?

@googlemaps/jest-mocks 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@googlemaps/jest-mocks 的下载量有多少?

根据 npm 官方下载统计,@googlemaps/jest-mocks 在 2026/10/17 – 2026/11/15 这 30 天内被下载 697,698 次,日均约 23,257 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@googlemaps/jest-mocks 还在维护吗?

最新版本 2.22.8 发布于 2026/02/11(9 个月前);至今共发布 72 个版本,其中过去 12 个月发布了 1 个;首次发布于 2019/11/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。