Imitation Google Maps object featuring TypeScript definitions

My Angular component relies on the google.maps.Map class. Here's what it looks like:

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

To install Google Maps type definitions, I followed the instructions in the documentation:

npm i -D @types/google.maps

Now, I'm trying to write unit tests for my component using an approach from a helpful SO answer (I use Karma for testing):

window['google'] = {
    maps: {
        Map: () => ({})
    }
};
const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({});

I encounter 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've tried various techniques, like

Map: () => { return {} as google.maps.Map }
, but TypeScript keeps showing type errors.

How can I substitute any object for the google.maps.Map type?

Answer №1

After some troubleshooting, I was able to resolve the issue by including any at the end of the mock object:

googleMaps = jasmine.createSpyObj('Maps', ['setCenter', 'setZoom', 'setOptions']);

function Map() {
    return googleMaps;
}

window['google'] = {
    maps: {
        Map: Map,
        ...
    }
} as any; // <---

Answer №2

To successfully cast the {}, you can do it this way:

const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({} as Map);

If that method doesn't work, you have the option to use any:

const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({} as any);

Alternatively, you could try this edit:

window['google'] = {
    maps: {
        Map: () => ({}) as any,
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Working with Files in TypeScript

New to TypeScript and seeking a command to eliminate the file path and extension. For example, if my file is located at ./data/input/myfile.js, how can I extract only "myfile" without the path and extension? ...

How to transform an array of Objects into a regular array using IONIC technology?

I'm currently working on converting an Object array into a regular array in HTML without using the "let item of array" method. Despite my extensive googling, I haven't found a solution that works thus far. Why am I avoiding loops? Well, because ...

Counting the total number of items and the total price in an Angular reactive form array

Looking to determine the Item Total Price and Total Price in a medicine store invoice system. How can I retrieve the ItemTotal and SubTotal values? I have added Medicine items as lines, but unsure how to calculate the Total Price for all Items. medicinepu ...

The Challenge of Deep Linking in Angular 2

When I attempt deep linking by requesting a URL like this: my-domain.com/my-appname/aRoute, everything works fine. However, if I visit my-domain.com/my-appname/aRoute/ system.js mistakenly looks for my main.js file at my-domain.com/my-appname/aRoute/app/ma ...

What is causing the error to appear in my Jasmine unit test?

Embarking on my journey to implement an Angular Unit Test using Jasmine for the first time, I encountered a few challenges after referring to some examples. The crux of my issue lies in the implementation of the PeopleListComponent class which encapsulate ...

Having troubles with *ngFor in Angular 8? Learn how to use ng-template effectively

I need assistance creating a table with dynamically generated columns and using the PrimeNg library for the grid. Despite asking several questions, I have not received any responses. Can someone please help me achieve this? To generate table column heade ...

Customize the dropdown width of the typeahead feature in ng-bootstrap

I recently started using the ng-bootstrap Typeahead component and so far, I am quite satisfied with it. One thing I am trying to figure out is how to make the width of the dropdown items in sync with the input field width. Currently, the default behavior ...

finding corresponding key in ngFor

I am curious to see if it is possible to match a key in *ngfor. Here is an example of my code on StackBlitz. However, when I try this method, it only displays No data. HTML <ul> <li *ngFor="let course of courses; index as i"> ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

Deactivate the Mention and Hash tag in ngx-linkifyjs

I am currently utilizing ngx-linkifyjs to automatically convert URLs in text to clickable hyperlinks. However, I am facing an issue where it is also converting # and @ tags into links. Is there a way to prevent the conversion of # and @ while maintain ...

Is it possible to import both type and value on the same line when isolatedModules=true?

Did you know with Typescript, you can do type-only imports? import type { Foo } from "./types" If the file exports both types and values, you can use two separate import statements like this: import type { Foo } from "./types"; import ...

The seamless integration of LIFERAY and Angular

I have been attempting to execute the example project from https://github.com/liferay/liferay-blade-samples/tree/7.0/gradle/apps/npm/angular-npm-portlet, but encountered a strange error after running npm install and npm run build. The error I received was ...

Angular 6's Nested HTTP Calls Issue: How to Ensure Nested Calls are Executed

Currently, while working with Angular 6, I am facing an issue with two HTTP calls that need to be executed sequentially. The first call is successful, but the second call shows success without actually sending an HTTP request. Interestingly, when I separa ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

What steps can be taken to effectively build a test suite architecture using Jest?

After exploring all the available resources on the Jest documentation website, including various guides and examples, I have yet to find a solution to my specific question. I am in search of a methodology that would enable me to individually run test case ...

Include a string in every tuple

I am trying to define a new type: type myNewType = 'value-1' | 'value-2' | 'value-3' Is there a way to create another type like this? type myNewType2 = '1' | '2' | '3' However, I want the outpu ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Having trouble using the 'in' operator to search for 'Symbol(StrapiCustomCoreController)' while transitioning Strapi to TypeScript

I'm in the process of converting my strapi project to typescript. I've updated all strapi packages to version 4.15.5 and converted the files to ts extension. However, upon running strapi develop, I encounter the following error: [2024-01-03 10:50 ...

Error encountered in ngOnInit when unit testing services: 'map is not a function'

While attempting to test a component using Jasmine & Karma, I encountered an unfamiliar error. Specifically, when trying to determine if my services have been called in ngOnInit(), I received the following error message: Failed: Uncaught (in promise): ...

An in-depth guide on leveraging the react-router useSubmit hook in combination with input onChange and button onClick events

I'm currently working on creating a search bar with a clear button using the useSubmit hook from react-router. The goal is to submit the search query both on input change and button click. SearchBar.tsx import { Form, useSubmit } from 'react-rou ...