Skip to content

Commit

Permalink
fix(mock-doc): support toDataURL method in canvas (#5773)
Browse files Browse the repository at this point in the history
* fix(mock-doc): support toDataURL method in canvas

* revert getImageData implementation

* make types more strict
  • Loading branch information
christian-bromann authored May 23, 2024
1 parent f21debc commit 3830dad
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 37 deletions.
86 changes: 49 additions & 37 deletions src/mock-doc/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -502,47 +502,59 @@ export class MockUListElement extends MockHTMLElement {
}
}

type CanvasContext = '2d' | 'webgl' | 'webgl2' | 'bitmaprenderer';
export class CanvasRenderingContext {
context: CanvasContext;
contextAttributes: WebGLContextAttributes;
constructor(context: CanvasContext, contextAttributes?: WebGLContextAttributes) {
this.context = context;
this.contextAttributes = contextAttributes;
}
fillRect() {
return;
}
clearRect() {}
getImageData(_: number, __: number, w: number, h: number) {
return {
data: new Array(w * h * 4),
};
}
toDataURL() {
return 'data:,'; // blank image
}
putImageData() {}
createImageData(): ImageData {
return {} as ImageData;
}
setTransform() {}
drawImage() {}
save() {}
fillText() {}
restore() {}
beginPath() {}
moveTo() {}
lineTo() {}
closePath() {}
stroke() {}
translate() {}
scale() {}
rotate() {}
arc() {}
fill() {}
measureText() {
return { width: 0 };
}
transform() {}
rect() {}
clip() {}
}

export class MockCanvasElement extends MockHTMLElement {
constructor(ownerDocument: any) {
super(ownerDocument, 'canvas');
}
getContext() {
return {
fillRect() {
return;
},
clearRect() {},
getImageData: function (_: number, __: number, w: number, h: number) {
return {
data: new Array(w * h * 4),
};
},
putImageData() {},
createImageData: function (): any[] {
return [];
},
setTransform() {},
drawImage() {},
save() {},
fillText() {},
restore() {},
beginPath() {},
moveTo() {},
lineTo() {},
closePath() {},
stroke() {},
translate() {},
scale() {},
rotate() {},
arc() {},
fill() {},
measureText() {
return { width: 0 };
},
transform() {},
rect() {},
clip() {},
};
getContext(context: CanvasContext, contextAttributes?: WebGLContextAttributes): CanvasRenderingContext {
return new CanvasRenderingContext(context, contextAttributes);
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/mock-doc/test/element.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,4 +514,11 @@ describe('element', () => {
expect(doc.createElement('svg').localName).toBe('svg');
expect((document.childNodes[1] as any).localName).toBe('html');
});

it('has provides a canvas object with getContext', () => {
const canvas = doc.createElement('canvas');
const ctx = canvas.getContext('2d');
expect(ctx).toBeDefined();
expect(ctx.toDataURL()).toBe('data:,');
});
});

0 comments on commit 3830dad

Please sign in to comment.