Mock Google 带有打字稿定义的地图对象
Mock Google Maps object with typescript definitions
我有一个 Angular 组件依赖于 google.maps.Map
class。看起来像这样:
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);
}
}
我根据 docs:
安装了 Google 地图类型定义
npm i -D @types/google.maps
现在我需要为我的组件创建单元测试并尝试使用以下方法SO answer(我使用 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,
}
};
我设法通过将 any
添加到模拟对象的末尾来修复它:
googleMaps = jasmine.createSpyObj('Maps', ['setCenter', 'setZoom', 'setOptions']);
function Map() {
return googleMaps;
}
window['google'] = {
maps: {
Map: Map,
...
}
} as any; // <---
我有一个 Angular 组件依赖于 google.maps.Map
class。看起来像这样:
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);
}
}
我根据 docs:
安装了 Google 地图类型定义npm i -D @types/google.maps
现在我需要为我的组件创建单元测试并尝试使用以下方法SO answer(我使用 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,
}
};
我设法通过将 any
添加到模拟对象的末尾来修复它:
googleMaps = jasmine.createSpyObj('Maps', ['setCenter', 'setZoom', 'setOptions']);
function Map() {
return googleMaps;
}
window['google'] = {
maps: {
Map: Map,
...
}
} as any; // <---