raju
raju

Reputation: 6936

JEST testing canvas and ctx

I have created a method to get image base64 using canvas, i want to unit test it using jest in angular:

 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;
  }

in unit testing doing like this:

 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();
  }));

I am getting error that TypeError: ctx.drawImage is not a function, in my UT trackImageOnload(); is for mocking the imageonload, it is working as expected.

Need some help.

I have already added jest-canvas-mock

Upvotes: 3

Views: 3083

Answers (1)

code-gorilla
code-gorilla

Reputation: 2418

Other than Karma, Jest does not run in a browser, it uses jsdom to simulate the dom interaction. In the jsdom docs it is mentioned, that an additional package must be installed for using the canvas.

While doing some research, I also found there is a package called jest-canvas-mock that provides a mock for Jest tests. This probably is the best solution for writing a component test.

Upvotes: 0

Related Questions