How to add <canvas> support to my tests in Jest? How to add <canvas> support to my tests in Jest? reactjs reactjs

How to add <canvas> support to my tests in Jest?


For those looking for examples using create-react-app

Install

yarn add --dev jest-canvas-mock

Create a new ${rootDir}/src/setupTests.js with

import 'jest-canvas-mock';


It's because your test doesn't run in a real browser. Jest uses jsdom for mocking the necessary parts of the DOM to be able to run the tests in Node, thus avoiding style calculation and rendering that a browser would normally do. This is cool because this makes tests fast.

On the other hand, if you need browser APIs in your components, it's more difficult than in the browser. Luckily, jsdom has support for canvas. You just have to configure it:

jsdom includes support for using the canvas package to extend any <canvas> elements with the canvas API. To make this work, you need to include canvas as a dependency in your project, as a peer of jsdom. If jsdom can find the canvas package, it will use it, but if it's not present, then <canvas> elements will behave like <div>s.

Alternatively, you could replace Jest with some browser-based test runner like Karma. Jest is pretty buggy anyway.


For my use case I did simple monkey patching like this

beforeEach(() => {    const createElement = document.createElement.bind(document);    document.createElement = (tagName) => {        if (tagName === 'canvas') {            return {                getContext: () => ({}),                measureText: () => ({})            };        }        return createElement(tagName);    };});

No need to install canvas-prebuilt or sinon.