首页 > 解决方案 > Angular 6 导入 Karma 测试中使用的 3rd 方 JS 文件的正确方法

问题描述

我有一个使用 primeng 的组件,ChartsModule它引用Chart.js. 我已经Chart.js安装并将它导入到我的angular.json文件中。

"scripts": [
  "node_modules/chart.js/dist/Chart.bundle.min.js"
]

该应用程序一切正常并显示图表。但是,我的组件测试因错误而中断:ReferenceError: Chart is not defined

我看过一些文章建议将 Chart.js 导入到我的组件测试中,如下所示:

import { Chart } from 'chart.js';

这行不通。我的问题是将 3rd 方 JS 库(例如 Chart.js)导入 Angular 6 Karma 测试的正确方法是什么

编辑 我的组件

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-my-chart',
  templateUrl: './my-chart.component.html',
  styleUrls: ['./my-chartcomponent.scss']
})
export class MyChartComponent implements OnInit {

  public data: any;

  constructor() { }

  ngOnInit() {
    this.data = {
      labels: ['Low', 'Medium', 'High'],
      datasets: [
        {
          data: [300, 50, 10],
          backgroundColor: [
              '#43a047',
              '#fb8c00',
              '#e53935'
          ],
          hoverBackgroundColor: [
              '#66bb6a',
              '#ffa726',
              '#ef5350'
          ]
        }]
      };
  }
}

标签: angulartypescripttestingkarma-runner

解决方案


还在用旧angular-cli.json模式思考。在新angular.json版本中有一个测试部分,您还必须在其中添加第 3 方脚本。

    "test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "main": "src/test.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "src/tsconfig.spec.json",
        "karmaConfig": "src/karma.conf.js",
        "styles": [
          "styles.scss"
        ],
        "scripts": [
          "node_modules/chart.js/dist/Chart.bundle.min.js"
        ],
        "assets": [
          "src/favicon.ico"
        ]
      }
    },

推荐阅读