为 Google 地图提供 Jest Mocks
说明
Jest为Google地图在TypeScript中进行取笑.
说明: 如果你找到一个丢失的模型,请 提交问题。 。 。 .
所需资源
- 与 Google 地图平台签约
- 谷歌地图平台 项目 与 地图 Javascript API 启用
- 一个 API 密钥 与上述项目有关的
- 节点js和国家预防机制
安装
国家防范机制作为一揽子方案提供 @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 服务器。 。 。 .
