【发布时间】:2021-02-03 06:01:27
【问题描述】:
我已经创建了一种使用画布获取图像 base64 的方法,我想使用 angular 中的 jest 对其进行单元测试:
getExistingImagebase64() {
const img = new Image();
img.crossOrigin = 'Anonymous';
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
img.onload = () => {
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img, 0, 0);
const uri = canvas.toDataURL('image/png');
const b64 = uri.replace(/^data:image.+;base64,/, '');
this.companyGroupForm.patchValue({
cgFormGroup: {
logo: b64
},
});
this.populateForm(this.receivedItemFromNavigation);
};
const url = this.receivedItemFromNavigation.logo;
img.src = url;
}
在单元测试中这样做:
it('should mark form as valid on edit scenario', fakeAsync(() => {
TestBed.overrideProvider(Router, { useValue: new MockRouter('/edit') });
TestBed.compileComponents();
fixture = TestBed.createComponent(GroupCompanyAddComponent);
component = fixture.componentInstance;
trackImageOnload();
const formSubmitSpy = spyOn(component, 'submitEditDataToApi').and.callThrough();
const successDialogSpy = spyOn(component, 'successDialog').and.callThrough();
fixture.detectChanges();
tick(1000);
imageOnload();
fixture.detectChanges();
fixture.whenStable();
tick(1000);
expect(component.companyGroupForm.valid).toBeTruthy();
}));
我收到错误消息,TypeError: ctx.drawImage is not a function 在我的 UT 中 trackImageOnload(); 用于模拟 imageonload,它按预期工作。
需要帮助。
我已经添加了 jest-canvas-mock
【问题讨论】: