我有一个导入 Chart.js/auto 并创建饼图的组件。组件和文件运行良好,当我运行 spec.ts 文件时,出现 TypeError: auto_1.default is not a constructor on the new Chart line。
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 不将其视为构造函数?
我面临着同样的问题,我通过模拟导入解决了它。我对测试 Chart.js 不感兴趣,所以我认为仅使用模拟对象没有任何问题。
我在
chart-stub.ts
文件中创建了一个模拟对象,如下所示:
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 会自动将任何实例替换为您的模拟类,并且能够用它创建一个新对象。