Code snippets already published in How to test SVG Graphs. Includes only article code, not additional private repository source. --- jsx --- import React from "react"; import { BarChart, YAxis, Bar } from "recharts"; export default function BarGraph({ data, width = 500, height = 500 }) { return ( ({ y: value }))} margin={{ top: 20, right: 20, left: 20, bottom: 20 }} > ); } --- jsx --- import React from "react"; import BarGraph from "./"; import { wait, render, screen } from "@testing-library/react"; describe("BarGraph", () => { describe("given two data points at a particular size", () => { const data = [40, 60]; const size = { width: 500, height: 1000 }; let graphContainer; beforeEach(() => { const { container } = render(
); graphContainer = container; }); }); }); --- jsx --- describe("BarGraph", () => { describe("given two data points at a particular size", () => { // It's super handy to use .each for graphs test.each` index | height | x | y ${0} | ${"640"} | ${"100"} | ${"340"} ${1} | ${"960"} | ${"300"} | ${"20"} `("renders rects", async ({ index, height, x, y }) => { // waits for rectangles to appear due to animation in graph library await wait(() => { // Hard coding classes is not ideal but best we have to work with const bars = graphContainer.querySelectorAll(".recharts-rectangle"); expect(bars[index].getAttribute("height")).toBe(height); expect(bars[index].getAttribute("x")).toBe(x); expect(bars[index].getAttribute("y")).toBe(y); }); }); }); }); --- jsx --- describe("BarGraph", () => { describe("given two data points at a particular size", () => { test.each` value | x | y ${"15"} | ${"72"} | ${"740"} ${"30"} | ${"72"} | ${"500"} ${"45"} | ${"72"} | ${"260"} ${"60"} | ${"72"} | ${"20"} `("displays $value in the correct position", ({ value, x, y }) => { // By testing the position of the tick we are also testing it existence, it's a two for one deal. const textNode = screen.getByText(value).parentNode; expect(textNode.getAttribute("y")).toBe(y); expect(textNode.getAttribute("x")).toBe(x); }); }); }); --- javascript --- expect(textNode).toMatchSnapshot() --- javascript --- exports[ `BarGraph given two data points at a particular size displays 15 in the correct position 1` ] = ` 15 ` --- javascript --- const textNode = screen.getByText(value).parentNode expect(textNode.getAttribute("y")).toBe("") expect(textNode.getAttribute("x")).toBe("") --- --- BarGraph › given two data points at a particular size › displays 15 in the correct position expect(received).toBe(expected) // Object.is equality Expected: "" Received: "740" --- javascript --- const textNode = screen.getByText(value).parentNode expect(textNode.getAttribute("y")).toMatchSnapshot() expect(textNode.getAttribute("x")).toMatchSnapshot()