Angular JEST测试画布和ctx
我创建了一个使用canvas获取图像base64的方法,我想在angular中使用jest对其进行单元测试:Angular JEST测试画布和ctx,angular,jestjs,Angular,Jestjs,我创建了一个使用canvas获取图像base64的方法,我想在angular中使用jest对其进行单元测试: getExistingImagebase64() { const img = new Image(); img.crossOrigin = 'Anonymous'; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); img
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();
}));
在我的UTtrackImageOnload()中,我得到的错误是TypeError:ctx.drawImage不是一个函数
代码>用于模拟imageonload,它按预期工作
我需要一些帮助
我已经添加了jest canvas mock除了Karma,jest不在浏览器中运行,它使用jsdom模拟dom交互。
在本文中提到,必须安装一个额外的包才能使用画布
在做一些研究时,我还发现有一个名为的包,它为Jest测试提供了一个模拟。这可能是编写组件测试的最佳解决方案。关于堆栈溢出,有几个问题可以通过“只需安装jest canvas mock,下面介绍如何执行‘设置文件’”来回答。如果这些答案包括一个完整的示例测试,那将非常有用。。。只需一个简单的测试就可以了,但要展示如何使用jest canvas mock。