TypeError:使用Jest和Chart.js进行单元测试时,auto_1.default不是构造函数,Chart构造函数

zte4gxcn  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(188)

我有一个导入chart.js/auto并创建饼图的组件。组件和文件运行正常,当我运行spec.ts文件时,我得到TypeError:auto_1.default不是新图表行上的构造函数。
chart.js 3.9.1
jest-canvas-mock 2.4.0
ng-mocks 14.2.3
从我的文件摘录(这工作):

import Chart from 'chart.js/auto'
.
.
.
myChart: Chart;
createChart(){
   this.myChart = new Chart(this.ctx, this.config);
}

spec.ts文件摘录:

.
.
.
import Chart from 'chart.js/auto';

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

   beforeEach(async(() => {
   TestBed.configureTestingModule({
       declarations: [myComponent, MockComponent(otherComponent)],
       imports: [myModules],
       providers: [Utilities, Services]
     }).compileComponents();
     fixture = TestBed.createComponent(myComponent);
     component.fixture.componentInstance;
     fixture.detectChanges();
   }));

   describe('createChart()', () => {
       it('should exist', () => {
          component.createChart();
          expect(component.createChart).toBeCalled();
       }
   })
}
MyComponent > createChart() > should exist
  TypeError: auto_1.default is not a constructor
     this.myChart = new Chart(this.ctx, this.config);
                    ^

为什么文件可以正常工作,图表可以正确创建和使用,但Jest不将其视为构造函数?

l2osamch

l2osamch1#

我也遇到了同样的问题,我只是通过嘲笑进口来解决它。我对测试chart.js不感兴趣,所以我认为使用mock对象没有任何问题。
我在chart-stub.ts文件中创建了一个mock对象,如下所示:

export class Chart {
  public canvas;
  public options;
  public data;
  // this is not a complete mock. You may need to mock other properties as well.

  public constructor(canvas: any, options: any) {
    this.canvas = canvas;
    this.options = options;
    this.data = options.data;
  }
}

然后在你的jest.config.ts中,你可以像这样交换它:

{
  displayName: 'YourProject',
  moduleNameMapper: {
    'chart.js/auto$': '<rootDir>/src/app/whatever-location/chart-stub.js'
  }
}

再运行一次。Jest将自动为您的mock类交换任何示例,并能够使用它创建一个新对象。

相关问题