首页 > 解决方案 > 使用打字稿定义模拟 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类型。

标签: angulartypescriptgoogle-mapskarma-jasmine

解决方案


尝试{}像这样投射:

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

推荐阅读