How To Test Canvas In Jest

Are you unsure of how to test Canvas using Jest? You’ve come to the correct location. This blog post will provide a detailed walkthrough of how to utilize Jest, a pleasant JavaScript Testing Framework, to effectively test your Canvas implementation.

Step 1: Install Jest and Jest-Canvas-Mock

Firstly, you need to install both Jest and Jest-Canvas-Mock into your project. Jest-Canvas-Mock is a package that allows you to mock canvas when you are testing with Jest. To install both, you can use npm or yarn commands:

npm install --save-dev jest jest-canvas-mock


yarn add --dev jest jest-canvas-mock

Step 2: Setup Jest

Next, you need to set up Jest in your project. Create a jest.config.js file at the root of your project and configure Jest to use jest-canvas-mock:

module.exports = {
  setupFiles: ['jest-canvas-mock'],

Step 3: Writing Your Test

Now, you are ready to write your tests. Ideally, you want to test your functions that interact with the Canvas API. Here’s an example:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

describe('Canvas Test', () => {
  test('Check if a rectangle is drawn', () => {
    // Your function that draws a rectangle

    // Check if fillRect was called

In the example above, we first create a mock canvas and get its 2D context. Then, we have a Jest test that checks if a rectangle is drawn. We call our function to draw a rectangle, and then we expect that the fillRect method of the context was called.

Step 4: Run Your Test

Finally, you can run your test using Jest command:

npm test


yarn test

If everything is set up correctly, you should see your tests pass!


As you can see, testing canvas with Jest is not very complicated. With the help of the jest-canvas-mock package, you can easily test your canvas interactions and ensure they work as expected. Happy testing!