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

Angular单元测试报错:window未找到Plotly,求测试环境引入方法

解决Angular单元测试中Plotly未找到的问题

Karma测试环境不会自动读取index.html(你提到的main.html)里引入的脚本,所以需要单独配置测试环境加载Plotly,以下是三种可行方案:

方案1:修改Karma配置文件加载脚本

打开项目根目录的karma.conf.js,找到files数组,添加Plotly脚本的路径:

module.exports = function (config) {
  config.set({
    // 保留原有配置
    files: [
      // 替换为你的Plotly脚本实际路径
      './path/to/plotly.min.js',
      // 原有文件配置
    ],
    // 保留原有配置
  });
};

如果是通过npm安装的Plotly(比如npm install plotly.js-dist),直接用node_modules路径更方便:

files: [
  './node_modules/plotly.js-dist/plotly.min.js',
],

方案2:在测试中模拟Plotly对象(无需真实脚本)

如果单元测试不需要渲染真实图表,只想绕过依赖检查,可以手动给window对象模拟Plotly:
在组件的.spec.ts文件里添加:

beforeEach(() => {
  // 模拟你用到的Plotly方法,按需添加
  (window as any).Plotly = {
    newPlot: jasmine.createSpy('newPlot'),
    restyle: jasmine.createSpy('restyle'),
    react: jasmine.createSpy('react')
  };

  TestBed.configureTestingModule({
    imports: [PlotlyViaWindowModule],
    // 其他测试配置
  });
});

方案3:通过Angular CLI配置测试脚本

打开angular.json,定位到projects -> 你的项目名 -> architect -> test -> options,添加scripts配置:

"test": {
  "builder": "@angular-devkit/build-angular:karma",
  "options": {
    // 原有配置
    "scripts": [
      "./path/to/plotly.min.js"
    ]
  }
}

使用npm安装的Plotly时,路径替换为./node_modules/plotly.js-dist/plotly.min.js即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:06:23