angular - 使用打字稿定义模拟 Google Maps 对象
问题描述
我有一个依赖于google.maps.Map
类的 Angular 组件。它看起来像这样:
export class MapViewComponent implements OnInit {
@Input()
public mapOptions: google.maps.MapOptions;
public map: google.maps.Map;
@ViewChild("map", { static: true })
mapDomNode: ElementRef;
public ngOnInit() {
this.map = new google.maps.Map(this.mapDomNode.nativeElement, this.mapOptions);
}
}
我根据文档安装了谷歌地图类型定义:
npm i -D @types/google.maps
现在我需要为我的组件创建单元测试并尝试使用以下SO 答案中的方法(我使用 Karma 进行测试):
window['google'] = {
maps: {
Map: () => ({})
}
};
const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({});
我得到错误:
Type '() => {}' is not assignable to type 'typeof Map'.
Type '() => {}' provides no match for the signature 'new (mapDiv: Element, opts?: MapOptions): Map'.ts(2322)
index.d.ts(3223, 9): The expected type comes from property 'Map' which is declared here on type 'typeof maps'
我尝试使用不同的变体,比如Map: () => { return {} as google.maps.Map }
和许多其他东西,但 TypeScript 总是显示类型错误。
如何使用任何对象而不是google.maps.Map
类型。
解决方案
尝试{}
像这样投射:
const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({} as Map);
如果这不起作用,您可以使用any
:
const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({} as any);
编辑尝试:
window['google'] = {
maps: {
Map: () => ({}) as any,
}
};
推荐阅读
- javascript - 我在这里调用哪个 createReadStream?
- r - 当使用 gseGO 函数在 R 中选择所有基因时未定义 GSEA 统计
- bash - 我们可以将多个 .gz 文件压缩到 gz 文件上吗
- flutter - 无法访问 Futurebuilder 中的 Snapshot.data
- vue.js - Vuejs 获取动态表单值
- ruby-on-rails - 日志说“fe_sendauth:没有提供密码”,但 rails 控制台工作没有问题
- python - 从其他函数注释派生的 Python 类型提示
- pandas - 用零替换所有 NaN 值的函数:
- excel - 如何在循环中将多个文件附加到消息中?
- bash - 用于检查在运行命令后是否在目录上创建了新文件的 Bash 脚本