【问题标题】:Angular Googlemaps typing fails unit testsAngular Googlemaps 输入未通过单元测试
【发布时间】:2018-03-24 09:39:58
【问题描述】:

我正在为一个 Angular 应用程序输入 @typings/googlemaps,该应用程序在运行时不会返回任何警告或错误。

但是,我想为我的组件创建一些单元测试,但 Karma 无法启动,产生如下错误:

ERROR in: ... Cannot find namespace 'google'.

我关注this post 和其他喜欢它的人来安装打字并继续我的工作。

declare var google:any 添加到 typings.d.ts 将不起作用,因为它已经在类型文件中声明,并且给出了“重复标识符”编译错误。

有什么建议吗?

编辑 1:

我的 google-maps.service.ts 上的代码摘录,其中一个文件给出了错误。我不导入 googlemaps,因为它不是必需的,因为它是我理解的打字。

import {Injectable} from "@angular/core";
import {environment} from "../../../environments/environment";
import {Http} from "@angular/http";
import {forEach} from "@angular/router/src/utils/collection";

@Injectable()
export class GoogleMapsService {
    scriptLoadingPromise: Promise<void>;

    api_key = '';
    url = '';

    map: google.maps.Map;
    markers: Array<google.maps.Marker>;
    bounds: google.maps.LatLngBounds;
    geocoder: google.maps.Geocoder;

    constructor(private http: Http) {
        this.api_key = '1234';
        this.url = 'https://maps.googleapis.com/maps/api/js';
        this.markers = new Array();
        // Loading script
        this.load().then(() => {
            this.geocoder = new google.maps.Geocoder();
        });
    }
}

getScriptSrc(callbackName: string): string {
    return `https://maps.googleapis.com/maps/api/js?key=${this.api_key}&callback=${callbackName}`;
};

onReady(): Promise<void> {
    return this.scriptLoadingPromise;
};

load(): Promise<void> {
    if (this.scriptLoadingPromise) {
        return this.scriptLoadingPromise;
    }

    const script = window.document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.defer = true;
    const callbackName = 'googleMapsServiceCallback';
    script.src = this.getScriptSrc(callbackName);

    this.scriptLoadingPromise = new Promise<void>((resolve: Function, reject: Function) => {
        (<any>window)[callbackName] = () => {
            resolve();
        };

        script.onerror = (error: Event) => {
            reject(error);
        };
    });
    window.document.body.appendChild(script);

    return this.scriptLoadingPromise;
}

编辑 2:我更新了上面的代码。它使用与Angular 2+ Maps 项目相同的结构,参考code here。由于键入时考虑了“google”关键字,因此没有引发任何预编译错误。

【问题讨论】:

  • 您能否分享您的代码 - 例如,在生成此错误的文件中,您是否有 googlemaps 的导入?
  • @Fenton - 添加了一些代码

标签: angular google-maps unit-testing typescript


【解决方案1】:

您需要向编译器提示您正在使用谷歌地图...例如使用导入:

import { googlemaps } from 'googlemaps'; 

如果您不使用模块,则使用 ///&lt;reference... 注释。

【讨论】:

  • 嘿@Fenton - 这不会解决我的问题,我不会在代码中的任何地方使用“googlemaps”作为包,即使我为“google”添加导入,我也会得到提示找不到“google”包的错误:(
  • 将进一步更新我的帖子和代码以包含一些额外的指针。
猜你喜欢
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 2021-09-13
  • 2019-04-03
相关资源
最近更新 更多