Reputation: 4255
I have an Angular component that depends on the google.maps.Map
class. It looks like this:
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);
}
}
I installed Google Maps type definitions according to docs:
npm i -D @types/google.maps
Now I need to create unit tests for my component and try to use the approach from the following SO answer (I use Karma for testing):
window['google'] = {
maps: {
Map: () => ({})
}
};
const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({});
I get the error:
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'
I tried to use different variations, like Map: () => { return {} as google.maps.Map }
and many other things but TypeScript always shows type errors.
How can I use any object instead of the google.maps.Map
type.
Upvotes: 3
Views: 2272
Reputation: 4255
I managed to fix it by adding any
to the end of the mock object:
googleMaps = jasmine.createSpyObj('Maps', ['setCenter', 'setZoom', 'setOptions']);
function Map() {
return googleMaps;
}
window['google'] = {
maps: {
Map: Map,
...
}
} as any; // <---
Upvotes: 6
Reputation: 18859
Try casting the {}
like so:
const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({} as Map);
And if that doesn't work, you can use any
:
const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({} as any);
Edit Try:
window['google'] = {
maps: {
Map: () => ({}) as any,
}
};
Upvotes: 1