How to test an HTML canvas? Let’s see an example of visual regression testing with Cypress.

What is a canvas?

An HTML canvas is an element which can be drawn on the page with JavaScript. Consider the following example:

A simple canvas

To draw this rectangle we use JavaScript on an HTML <canvas> element. HTML canvas are everywhere, from HTML games to charts. A popular chart library for JavaScript, Chart.js uses canvas to draw beautiful charts.

Canvas are great and all, but they’re somewhat hard to test because of their nature. Let’s see how to test a canvas in this quick guide.

Setting up the project

To start off create a new folder and move into it:

mkdir testing-canvas && cd $_

Initialize a new JavaScript project:

npm init -y

Inside the project folder create an HTML document in index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Testing a Canvas</title>
</head>
<body>
<div>
    <canvas width="400" height="400">
        Alternative text
    </canvas>
</div>
</body>
<script>
    const canvas = document.querySelector('canvas');
    const context = canvas.getContext('2d');
    context.fillStyle = 'yellow';
    context.fillRect(20, 20, 200, 200);
</script>
</html>

To test that everything is in place run from inside the project folder:

npx serve

Then visit http://localhost:5000/, you should see the canvas:

A simple canvas

Let’s now discuss how to test such an element.

#html #javascript #testing

Testing an HTML canvas with Cypress
46.15 GEEK