【问题标题】:JEST testing canvas and ctxJEST 测试画布和 ctx
【发布时间】: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 在我的 UTtrackImageOnload(); 用于模拟 imageonload,它按预期工作。

需要帮助。

我已经添加了 jest-canvas-mock

【问题讨论】:

    标签: angular jestjs


    【解决方案1】:

    除了 Karma,Jest 不运行在浏览器中,它使用 jsdom 来模拟 dom 交互。 在jsdom docs 中提到,必须安装一个额外的包才能使用画布。

    在进行一些研究时,我还发现有一个名为 jest-canvas-mock 的包,它为 Jest 测试提供模拟。这可能是编写组件测试的最佳解决方案。

    【讨论】:

    • Stack Overflow 上有几个问题可以通过“只需安装 jest-canvas-mock 以及如何执行 'setupFiles'”来回答。如果这些答案包括一个完整的示例测试,那将非常有帮助......只是一个简单的测试就可以了,但显示 如何 jest-canvas-mock 的使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2019-06-17
    • 2014-04-05
    • 2019-07-27
    • 2019-07-31
    相关资源
    最近更新 更多