:last_quarter_moon: A module used to mock canvas in Jest.
Mock
canvaswhen run unit test cases with jest. For more browser environment, you can use jest-electron for real browser runtime.
This should only be installed as a development dependency (
devDependencies) as it is only designed for testing.
npm i --save-dev jest-canvas-mock
In your
package.jsonunder the
jest, create a
setupFilesarray and add
jest-canvas-mockto the array.
{ "jest": { "setupFiles": ["jest-canvas-mock"] } }
If you already have a
setupFilesattribute you can also append
jest-canvas-mockto the array.
{ "jest": { "setupFiles": ["./__setups__/other.js", "jest-canvas-mock"] } }
More about in configuration section.
Alternatively you can create a new setup file which then requires this module or add the
requirestatement to an existing setup file.
__setups__/canvas.js
import 'jest-canvas-mock'; // or require('jest-canvas-mock');
Add that file to your
setupFilesarray:
"jest": { "setupFiles": [ "./__setups__/canvas.js" ] }
This mock strategy implements all the canvas functions and actually verifies the parameters. If a known condition would cause the browser to throw a
TypeErroror a
DOMException, it emulates the error. For instance, the
CanvasRenderingContext2D#arcfunction will throw a
TypeErrorif the radius is negative, or if it was not provided with enough parameters.
// arc throws a TypeError when the argument length is less than 5 expect(() => ctx.arc(1, 2, 3, 4)).toThrow(TypeError);// when radius is negative, arc throws a dom exception when all parameters are finite expect(() => ctx.arc(0, 0, -10, 0, Math.PI * 2)).toThrow(DOMException);
The function will do
Numbertype coercion and verify the inputs exactly like the browser does. So this is valid input.
expect(() => ctx.arc('10', '10', '20', '0', '6.14')).not.toThrow();
Another part of the strategy is to validate input types. When using the
CanvasRenderingContext2D#fillfunction, if you pass it an invalid
fillRuleit will throw a
TypeErrorjust like the browser does.
expect(() => ctx.fill('invalid!')).toThrow(TypeError); expect(() => ctx.fill(new Path2D(), 'invalid!')).toThrow(TypeError);
We try to follow the ECMAScript specification as closely as possible.
There are multiple ways to validate canvas state using snapshots. There are currently three methods attached to the
CanvasRenderingContext2Dclass. The first way to use this feature is by using the
__getEventsmethod.
/** * In order to see which functions and properties were used for the test, you can use `__getEvents` * to gather this information. */ const events = ctx.__getEvents();expect(events).toMatchSnapshot(); // jest will assert the events match the snapshot
The second way is to inspect the current path associated with the context.
ctx.beginPath(); ctx.arc(1, 2, 3, 4, 5); ctx.moveTo(6, 7); ctx.rect(6, 7, 8, 9); ctx.closePath();/**
__getPath
method, that array will sliced and usable for snapshots.The third way is to inspect all of the successful draw calls submitted to the context.
ctx.drawImage(img, 0, 0);/**
In some cases it may be useful to clear the events or draw calls that have already been logged.
// Clear events ctx.__clearEvents();// Clear draw calls ctx.__clearDrawCalls();
Finally, it's possible to inspect the clipping region calls by using the
__getClippingRegionfunction.
const clippingRegion = ctx.__getClippingRegion(); expect(clippingRegion).toMatchSnapshot();
The clipping region cannot be cleared because it's based on the stack values and when the
.clip()function is called.
You can override the default mock return value in your test to suit your need. For example, to override return value of
toDataURL:
canvas.toDataURL.mockReturnValueOnce( 'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' );