(chartInit)在Karma / Jasmine测试中无法正常工作

时间:2018-07-19 08:28:23

标签: angular karma-runner echarts

关于使用echarts的组件的Angular Testing,我遇到了一些奇怪的问题。

在我的html中,我有以下div:

<div class="jmCanvas">
  <div id="usersLineChart" echarts [options]="optionUsersLineChart" (chartInit)="onChartInitUsersLine($event)" class="demo-chartUsers"></div>
</div>

而且,在组件中,我有这部分代码:

  onChartInitUsersLine(ec) {
    console.log("setLine");
    this.echartLine = ec;
  }

在onInit方法中:

console.log(this.echartLine.setOption);
this.echartLine.setOption(this.optionUsersLineChart);

成为根据模型更改的this.optionUsersLineChart选项文件。

这在正常运行应用程序时确实很好用,完全没有问题。

但是,使用以下命令运行spec.ts文件时:

import { async, ComponentFixture, TestBed, getTestBed } from '@angular/core/testing';

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { UsersViewComponent } from './users-view.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MyDateRangePickerModule } from 'mydaterangepicker';
import { NgxEchartsModule, NgxEchartsService } from 'ngx-echarts';
import { Observable } from 'rxjs';
import { SessionService } from '../Services/session.service';
import { SortingService } from '../sorting.service';
import { testSet } from '../test/testSet';
import { Session } from '../models/Session';

class MockService {
  getSessions(user: string, pageTitle: string, deviceType: string, browser: string, beginDate: number, endDate: number, os: string, screenRes: string,company:string): Observable<any[]> {
    return Observable.of(testSet);
  }      
}

describe('UsersViewComponent', () => {
  let component: UsersViewComponent;
  let service;
  let fixture: ComponentFixture<UsersViewComponent>;

  function fireEvent(id, event) {
    const nativeElement = fixture.nativeElement;
    const elem = nativeElement.querySelector('#' + id);
    elem.dispatchEvent(new Event(event));
  }

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule, ReactiveFormsModule, MyDateRangePickerModule, NgxEchartsModule, HttpClientTestingModule],
      declarations: [UsersViewComponent]
    }).overrideComponent(UsersViewComponent,{
      set: {
            providers: [
        NgxEchartsService,
        {provide:SessionService,useClass:MockService},
        SortingService
      ]
    }});
    fixture = TestBed.createComponent(UsersViewComponent);
    component = fixture.componentInstance;
    fireEvent("usersLineChart", "chartInit");
    fixture.detectChanges();
  });

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

它会引发以下错误:

TypeError: _this.echartLine.setOption is not a function

根据控制台日志,将触发该事件,但显然在图表实例中找不到该setOption函数。

有什么线索吗?

我已经尝试了很多方法,但现在我被这个错误困扰了一段时间。

1 个答案:

答案 0 :(得分:0)

最终成为一个async问题。据我所知,它在(chartInit)之后被称为onInit(),因此由于给定的错误而失败。事件发生后,我手动致电了onInit(),它解决了问题。