Vitest How to mock A Canvas

Vitest How to mock A CanvasIn this short guide, you will learn how to mock A HTML Canvas in Vitest .To have a real implementation for your SUT.
CategoriesdevHack testing javascript vitest
Date
2022-04-20
Hire me on Upwork!

Vitest is a new testing framework for JavaScript. It is fast and easy to get started when you have used JavaScript testing frameworks like jest before! Currently, it is still in beta, but I think it is already awesome!

When it comes to mocking, there is like with every framework some stuff to know. But for our luck, there are strong libraries which helps us!

To mock a canvas in Vitest this library is node-canvas and JSDom, I will show you how to set them up.

How to set up JSdom in Vitest

To install JSDom run

npm i jsdom

Next, we need to tell vitest to use JSDom, this happens in the test section of your vite.config.js.

import { defineConfig } from "vite";

export default defineConfig({
  plugins: [
    createVuePlugin(),
  ],
  resolve: {
    alias: [
      {
        find: "@",
        replacement: path.resolve(__dirname, "src"),
      },
    ],
  },
  test: {
    environment : "jsdom", // or 'node'
  },
});

JSDom is now ready To Use. Up next, we are going to use JSDom to mock jQuery in Vitest.

Vitest how to mock HTML Canvas?

With JSDom set up, we also need to install node canvas library. This is a peer dependency of JSDom and will be recognized automatically.

npm i canvas

Since this package does not work with node > 14 by default, you also need to run.

npm rebuild canvas --update-binary

To make the node canvas work with > node 14 which is required for vite.

Otherwise, you will get the error:

Module did not self-register: '...\node_modules\canvas\build\Release\canvas.node'

If the error still persists, set threads to false in your vite config.

test: {
    environment: "jsdom",
    threads: false,
  },

At least then it also works on Apple silicon with node 18.xx

To actually mock the canvas, simply write your HTML code for your test as you normally would.

const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p><canvas
                id="canvas"
              >
              </canvas>`);
    global.document = dom.window.document;

Then expose the created document as the global document.

That's it.

Conclusion

Mocking is sometimes hard, but once you got it, there are mostly some lines of code to handle everything! You just need to get the basic concepts and think around the edge about why simple mocking sometimes just does not work and how to set up everything properly as we did in this article.

I hope I could provide you with some value with this article. If you want to support me and the work I'm doing, you can buy me a coffee.

Happy testing,

Alex

Recommended Products for you
recommended for you