You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 20 Karma单元测试中Google Maps API加载异常问题

Angular v20 Karma单元测试中加载Google Maps API的修复方案

Angular v20对Karma的资源加载逻辑做了调整,原来直接在files数组中指定API文件的方式不再能保证优先加载,导致测试时找不到google命名空间。以下是几种可行的修复方式:

1. 调整Karma文件配置的属性

在karma.config.js中,给Google Maps API文件添加明确的加载属性,确保它被优先注入到测试页面:

module.exports = function (config) {
  config.set({
    // ...
    files: [
      {
        pattern: "src/assets/google-maps-api.js",
        included: true, // 强制注入到测试页面的script标签中
        serve: true, // 允许Karma提供该文件
        watched: false // 不需要监听文件变化,提升测试速度
      }
    ],
    // ...
  });
};

2. 提前声明或Mock google命名空间

如果API文件加载存在延迟,可在测试入口文件(比如test.ts)顶部添加全局声明和临时Mock,避免测试启动时直接报错:

// 在test.ts最顶部添加
declare global {
  interface Window {
    google: any;
  }
}

// 初始化空的google命名空间,后续API加载会覆盖这个临时对象
window.google = window.google || {
  maps: {
    Map: () => {},
    Marker: () => {},
    // 根据你的测试需求,Mock更多需要用到的类或方法
  }
};

3. 通过angular.json配置加载脚本

Angular v20推荐通过项目配置文件加载外部脚本,避免Karma配置被预设覆盖。修改angular.json中的测试配置:

{
  "projects": {
    "你的项目名称": {
      "architect": {
        "test": {
          "options": {
            "scripts": ["src/assets/google-maps-api.js"]
          }
        }
      }
    }
  }
}

这种方式会让Angular构建工具在测试环境中优先加载指定脚本,确保google命名空间在测试代码执行前可用。

内容的提问来源于stack exchange,提问作者Winthorpe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:22:46