@googlemaps/jest-mocks

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

[npm[npm-pkg] (英语) Release Stable [! [试/建] (https://github.com/go (英语)

中文使用文档
文档目录11 节
  1. 说明
  2. 所需资源
  3. 安装
  4. 使用量
  5. 测试事件
  6. 正在扩展模拟
  7. 模拟服务
  8. 清理模拟器
  9. 捐款
  10. 服务条件
  11. 支助

npm Release Stable Tests/Build

codecov semantic-release solidarity

Contributors License StackOverflow Discord

为 Google 地图提供 Jest Mocks

说明

Jest为Google地图在TypeScript中进行取笑.

说明: 如果你找到一个丢失的模型,请 提交问题。 。 。 .

所需资源

安装

国家防范机制作为一揽子方案提供 @googlemaps/jest-mocks

npm i @googlemaps/jest-mocks

使用量

这些模拟需要测试在类似浏览器的环境中运行(例如) jest-environment-jsdom) (中文(简体) ).

在运行测试前, 您必须调用导出 initialize 设置被嘲笑的 Google 地图 API 的全局命名空间的函数:

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

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

然后可以运行几乎像正常一样使用地图API的测试码. "几乎"指的是物体都是不起作用的,而且 有些事情你可以用真实的地图 API 无法用模拟 图书馆.

我们还出口 mockInstances 对象和被嘲笑的构造者 类别(例如:. Map 或者说 Marker可用于检索、检查和 配置模拟器 .

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

测试事件

要测试使用 Maps API 对象发送的事件的代码, 您可以 遵循这样的模式:

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

正在扩展模拟

有些情况下,你需要更多的功能 从模拟器 而不是这个图书馆提供的东西。 在这种情况下,您可以延长 已存在的模拟.

例如,如果想要观察创建地图实例到 验证构建器-参数,您可以添加这样的间谍函数 :

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

因此,基本上,你可以覆盖全球的班级 google.maps 名称空间,并带有您自己的扩展已有的类别。 这个 initialize 函数将永远恢复到初始状态.

模拟服务

如果您的代码与 Maps API 提供的服务相互作用, 您可以 控制调用方法时返回的结果 服务。 首先,您需要获得由 您使用的代码 mockInstances 登记:

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

注意进口 AutocompleteService 财务报告和审定财务报表 google.maps.places.AutocompleteService 是同一个对象. 唯一的区别是 前者是被嘲笑的版本 (这样你就可以在写作测试时访问模拟界面而不使用打字器) 在TS。 (中文(简体) ).

由于被嘲弄的方法是在被嘲弄者的构造者中创造出来的 AutocompleteService,我们不能覆盖 行为方法之前 构造器已被调用 .

如果自动完成服务的创建与它的用法分离, 这比较容易:

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

如果您可以以某种方式分离服务对象的创建,同样适用 例如,通过在试验中用猴子涂抹它:

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

这两种解决方案可能都是一种反派,因为它们 披露执行细节(如: service 属性或 createAutocompleteService 方法),使其更难改变 在不更新测试的情况下执行.

建议的方法是实现这一目标,即取代 AutocompleteService 完全控制它的行为:

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

清理模拟器

无论何时 initialize() 被称作, 被捕获的模拟器自动清理。 利用杰斯特的任何方法,你可以随时清理模拟事件:

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

捐款

欢迎和鼓励捐款! 如果你愿意,给我们一个 拉动请求 并提到我们的 行为守则 财务报告和审定财务报表 贡献指南。 。 。 .

服务条件

这个库使用谷歌地图平台服务. 通过此库使用 Google 地图平台服务受 Google 地图平台制约 服务条件。 。 。 .

这个库不是谷歌地图平台核心服务. 因此,Google地图平台服务条款(如技术支持服务,服务级别协议和折旧政策)不适用于本库中的代码.

支助

此库通过开源提供 许可证它不受Google地图平台支持[技术支持服务准则、SLA或 折旧政策然而,图书馆使用的任何Google Maps平台服务仍受Google Maps平台服务条款的约束.

此图书馆所遵循的 语义版本 以表示何时引入了倒向相容的更改。 因此,虽然库在"0.x"版本中,但可以随时引入与后相容的修改.

如果您找到错误, 或者有特性请求, 请 提交问题 (原始内容存档于2018-09-29). on GitHub. 如果您想从其他 Google 地图平台开发者那里得到技术问题的答案,请通过我们中的一个 开发者社区频道请检查date=中的日期值 (帮助) 贡献指南。 。 。 .

你可以在我们的图书馆里讨论 Discord 服务器。 。 。 .

版本与发布记录

@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] (英语) [! [试/建] (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 和提交记录判断。