How To Test Canvas In Cypress

In this article, we will explore the process of testing a canvas using Cypress, a well-known end-to-end testing tool for web-based applications. While testing a canvas may seem complex, Cypress simplifies it and makes it more manageable. So, let’s begin!

Overview on Canvas

The HTML canvas element is used to draw graphics on a web page. It’s a container for graphics, where we can draw using JavaScript.

Cypress and Canvas

Due to the nature of the canvas element, it’s hard to interact with or get information about its content in a test. Cypress operates by dispatching events and then asserting on the side effects of these actions, but graphics on a canvas do not have event listeners or DOM structures that could react to dispatched events.

Testing Approach

Although we can’t directly test the canvas, we can test the functionality that results in changes to the canvas. This involves testing the functions responsible for rendering the content in the canvas.

Example: Testing a Drawing Function

Suppose we have a function called drawRectangle that draws a rectangle on the canvas. We can test this function using Cypress as below:

    it('should draw a rectangle', () => {
        cy.window().then((win) => {
            cy.stub(win, 'drawRectangle').callsFake((x, y, width, height) => {
                // assertions or checks go here

            // trigger the function

In the above example, we’re using Cypress to get a reference to the window object, then we’re stubbing out the drawRectangle function. This allows us to make assertions about the values that the function is called with when the “draw-rectangle” button is clicked.


Testing canvas with Cypress can be tricky due to the nature of the canvas element. However, by shifting our focus to the functions that result in changes to the canvas, we can still ensure the correct behavior of our application.

We hope this blog post was helpful in your journey of mastering Cypress tests. Stay tuned for more such informative content. Happy testing!