# @googlemaps/jest-mocks 中文文档

规范地址：https://npmcn.com/package/%40googlemaps/jest-mocks/

版本：2\.22\.8
npm 元数据更新时间：2026-05-14T23:26:26.896Z
中文译文更新时间：2026-11-16T19:56:52.057Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40googlemaps/jest-mocks
原文对照：https://npmcn.com/package/%40googlemaps/jest-mocks/?lang=original
项目主页：https://github.com/googlemaps/js-jest-mocks
源码仓库：https://github.com/googlemaps/js-jest-mocks

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：234 kB，80 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2019-11-07T20:13:05.354Z
- 最新版本发布：2026-02-11T10:15:38.642Z
- 近 30 天下载量：697698（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：72（近 12 个月 1 个）

## 中文简介

\[![npm](https://img.shields.io/npm/v/@googlemaps/jest-mocks)\[npm-pkg\] (英语) ![Release](https://github.com/googlemaps/js-jest-mocks/workflows/Release/badge.svg) ![Stable](https://img.shields.io/badge/stability-stable-green) \[! \[试/建\] ([https://github.com/go (英语)](https://github.com/go)

## 安装

```sh
npm install @googlemaps/jest-mocks
```

也可以使用：`pnpm add @googlemaps/jest-mocks`、`yarn add @googlemaps/jest-mocks`、`bun add @googlemaps/jest-mocks`

## README

[![npm](https://img.shields.io/npm/v/@googlemaps/jest-mocks)](https://npmjs.com/package/@googlemaps/jest-mocks) ![Release](https://github.com/googlemaps/js-jest-mocks/workflows/Release/badge.svg) ![Stable](https://img.shields.io/badge/stability-stable-green) [![Tests/Build](https://github.com/googlemaps/js-jest-mocks/actions/workflows/test.yml/badge.svg)](https://github.com/googlemaps/js-jest-mocks/actions/workflows/test.yml)

[![codecov](https://codecov.io/gh/googlemaps/js-jest-mocks/branch/main/graph/badge.svg)](https://codecov.io/gh/googlemaps/js-jest-mocks) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![solidarity](https://github.com/jpoehnelt/in-solidarity-bot/raw/main/static//badge-flat.png)](https://github.com/apps/in-solidarity)

![Contributors](https://img.shields.io/github/contributors/googlemaps/js-jest-mocks?color=green) [![License](https://img.shields.io/github/license/googlemaps/js-jest-mocks?color=blue)](https://npmcn.com/package/%40googlemaps/jest-mocks/LICENSE) [![StackOverflow](https://img.shields.io/stackexchange/stackoverflow/t/google-maps?color=orange&label=google-maps&logo=stackoverflow)](https://stackoverflow.com/questions/tagged/google-maps) [![Discord](https://img.shields.io/discord/676948200904589322?color=6A7EC2&logo=discord&logoColor=ffffff)](https://discord.gg/hYsWbmk)

# 为 Google 地图提供 Jest Mocks

## 说明

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

**说明:** 如果你找到一个丢失的模型,请 [提交问题](https://github.com/googlemaps/js-jest-mocks/issues/new/choose)。 。 。 .

## 所需资源

-   [与 Google 地图平台签约](https://console.cloud.google.com/google/maps-apis/start)
-   谷歌地图平台 [项目](https://developers.google.com/maps/documentation/javascript/cloud-setup#enabling-apis) 与 [**地图 Javascript API**](https://developers.google.com/maps/documentation/javascript) 启用
-   一个 [API 密钥](https://developers.google.com/maps/documentation/javascript/get-api-key) 与上述项目有关的
-   节点js和国家预防机制

## 安装

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

```
npm i @googlemaps/jest-mocks
```

## 使用量

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

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

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

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

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

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

```ts
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 对象发送的事件的代码, 您可以 遵循这样的模式:

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

### 正在扩展模拟

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

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

```ts
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` 登记:

```ts
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`,我们不能覆盖 行为方法之前 构造器已被调用 .

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

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

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

```ts
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` 完全控制它的行为:

```ts
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()` 被称作, 被捕获的模拟器自动清理。 利用杰斯特的任何方法,你可以随时清理模拟事件:

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

## 捐款

欢迎和鼓励捐款! 如果你愿意,给我们一个 [拉动请求](https://github.com/googlemaps/js-jest-mocks/compare) 并提到我们的 [行为守则](https://npmcn.com/package/%40googlemaps/jest-mocks/?tab=coc-ov-file#readme) 财务报告和审定财务报表 [贡献指南](https://npmcn.com/package/%40googlemaps/jest-mocks/CONTRIBUTING.md)。 。 。 .

## 服务条件

这个库使用谷歌地图平台服务. 通过此库使用 Google 地图平台服务受 Google 地图平台制约 [服务条件](https://cloud.google.com/maps-platform/terms)。 。 。 .

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

## 支助

此库通过开源提供 [许可证](https://npmcn.com/package/%40googlemaps/jest-mocks/LICENSE)它不受Google地图平台支持\[技术支持服务准则、SLA或 [折旧政策](https://cloud.google.com/maps-platform/terms)然而,图书馆使用的任何Google Maps平台服务仍受Google Maps平台服务条款的约束.

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

如果您找到错误, 或者有特性请求, 请 [提交问题](https://github.com/googlemaps/js-jest-mocks/issues/new/choose) (原始内容存档于2018-09-29). on GitHub. 如果您想从其他 Google 地图平台开发者那里得到技术问题的答案,请通过我们中的一个 [开发者社区频道](https://developers.google.com/maps/developer-community)请检查date=中的日期值 (帮助) [贡献指南](https://npmcn.com/package/%40googlemaps/jest-mocks/CONTRIBUTING.md)。 。 。 .

你可以在我们的图书馆里讨论 [Discord 服务器](https://discord.gg/hYsWbmk)。 。 。 .

## 常见问题

### @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 和提交记录判断。

