【问题标题】:ng2-charts error while testing Angular app测试 Angular 应用程序时出现 ng2-charts 错误
【发布时间】:2020-06-16 03:54:49
【问题描述】:

当我使用包含图表的组件运行测试时,我收到错误 TypeError: Cannot read property 'getBasePixel' of undefined。我不确定发生了什么,我尝试查找内容,但没有找到任何相关的内容。我有测试导入图表模块,我真的想不出其他任何可能出错的地方。我唯一的想法可能是在异步 beforeEach 中导入的图表模块意味着它不能立即用于组件?或者可能因为它是在“较小”的浏览器中呈现的,所以它不能正常工作?我想不通。

我的测试如下所示:

import { HttpClientModule } from '@angular/common/http';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ChartsModule } from 'ng2-charts';
import { PlantsService } from '../plant/plants.service';
import { MockPlantsService } from '../plant/plants.service.mock';
import { DashboardComponent } from './dashboard.component';

describe('DashboardComponent', () => {
  let component: DashboardComponent;
  let fixture: ComponentFixture<DashboardComponent>;
  let plantsService: PlantsService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ChartsModule,
        HttpClientModule,
        RouterTestingModule,
      ],
      declarations: [
        DashboardComponent,
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        DashboardComponent,
        { provide: PlantsService, useClass: MockPlantsService },
      ],
    });
    fixture = TestBed.createComponent(DashboardComponent);
    component = fixture.componentInstance;
    plantsService = TestBed.inject(PlantsService);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

和组件:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { ChartDataSets, ChartOptions } from 'chart.js';
import { Color, Label } from 'ng2-charts';
import { Subscription } from 'rxjs';
import { Plant } from '../plant/plant.model';
import { PlantsService } from '../plant/plants.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],
})
export class DashboardComponent implements OnInit, OnDestroy {
  public isLoading = false;
  private plantSub: Subscription;
  private plantInfoSub: Subscription;
  public plantList: Plant[];
  public selectedPlant: Plant;

  // Chart configuration stuff goes here, Removed for brevity

  constructor(private plantsService: PlantsService) { }

  ngOnInit() {
    this.isLoading = true;
    this.plantsService.getPlants();
    this.plantSub = this.plantsService.getPlantsUpdateListener().subscribe((plantData: { plants: Plant[] }) => {
      this.isLoading = false;
      this.plantList = plantData.plants;
      if (this.plantList) {
        this.getPlantInfo(this.plantList[0]);
      }
    });
  }

  getPlantInfo(plant: Plant) {
    if (!plant) { return; }
    this.plantsService.getPlantInfo(plant.id);
    this.plantInfoSub = this.plantsService.getPlantInfoUpdateListener().subscribe((plantInfo: { plant: Plant }) => {
      plant = Object.assign(plant, plantInfo.plant);
      this.lineChartData = [Plant.getChartData(plant.humidityHistory, 'Humidity')];
      if (plant.soilMoistureHistory) {
        this.lineChartData.push(Plant.getChartData(plant.soilMoistureHistory, 'Soil Moisture'));
      }
      this.lineChartLabels = Plant.getPlantHistoryTimestamp(plant.humidityHistory);
    });
  }

  ngOnDestroy() {
    this.plantSub?.unsubscribe();
    this.plantInfoSub?.unsubscribe();
  }
}

编辑:

堆栈跟踪:

 at <Jasmine>
    at ChartElement.updateElement (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:5931:1)
    at ChartElement.update (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:5903:1)
    at ChartElement._update (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:3831:1)
    at ChartElement.reset (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:3733:1)
    at http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:9638:1
    at Object.each (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:2227:1)
    at Chart.update (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:9637:1)
    at Chart.construct (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:9357:1)
    at new Chart (http://localhost:9876/_karma_webpack_/node_modules/chart.js/dist/Chart.js:9294:1)
    at BaseChartDirective.getChartBuilder (http://localhost:9876/_karma_webpack_/node_modules/ng2-charts/__ivy_ngcc__/fesm2015/ng2-charts.js:677:1)

【问题讨论】:

  • 从您的错误消息中,似乎有一段代码试图调用或访问未定义对象的 getBasePixel 属性。因为getBasePixel 没有出现在您的代码示例中,它可能发生在不同的函数中。如果错误消息带有堆栈跟踪,则可能有助于诊断导致此错误的函数。否则你也可以尝试逐行注释代码,直到错误停止,以将问题缩小到导致它的行
  • @MoralCode 我在上面包含了一个堆栈跟踪。它似乎在我的代码之外。我想知道我是否应该切换到 ngx-charts,因为 ng2-charts 维护者不再维护它。
  • 这可能是您的` // 图表配置内容放在这里,为简洁而删除` 实际上可能是必要的。看起来github 上的ng2-charts 存在问题,cmets 中的某个人似乎有同样的错误,并通过将轴设置“放在选项中,而不是数据中”来解决它。希望对您有所帮助!
  • @MoralCode 这些东西在实际文件中的格式实际上是正确的,我删除了这篇文章的所有内容,因为堆栈溢出不允许我发布它,因为我的大部分问题都是代码。

标签: angular karma-jasmine ng2-charts


【解决方案1】:

我最终切换到 ngx-charts,因为不再维护 ng2-charts。测试期间没有问题了。

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    相关资源
    最近更新 更多