Automated Testing Charts in Canvas in Selenium WebDriver
How to verify the content in a canvas in Selenium WebDriver
--
In a previous article, I showed you how to test charts in an SVG format. Charts (and other diagrams) can also be embedded in a Canvas on a web page.
Test Site
In this tutorial I will use the demo bar chart on ChartJS’ website (link: https://www.chartjs.org/docs/latest/samples/bar/vertical.html).
Test Design
- Verify the chart is present by checking the
canvas
tag - Extract the Canvas & Save the chart to a file
- Verify the image file
Test Steps
1. Verify the chart exists
Right-click the chart to inspect, thecanvas
tag is highlighted.
HTML Source:
// ...
<div class="chart-view">
<canvas width="1175" height="586">
</canvas>
</div>
// ...
Verifying the existence of the canvas
tag is good enough for now (we will do further verification later).
canvas_elem = driver.find_element(:xpath, "//div/canvas")
# if it does not exist, the above will throw error
Rendering charts (by JavaScript) takes a short time, so add a minor wait. The complete test statements look like below.
driver.get("https://www.chartjs.org/docs/latest/samples/bar/vertical.html")
sleep 1 # wait for the canvas to load
canvas_elem = driver.find_element(:xpath, "//div/canvas")
However, we can not be sure that the chart is actually displayed correctly. The solution: save the chart as a PNG.