Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
testing chartjs canvas with jest

I have a chart (that works in browsers as expected in browsers) it is a react component that accepts an interger and then adds the point to the graph with the desired value, the graph also throws away data if there are more than x(40) datapoints on the graph.

I am using jest-canvas-mock to have a useable snapshot for my graph but it just returns nonsense.

Here is my test;

beforeAll(() => {
        class ResizeObserver {
            observe() {}
            disconnect() {}
        }
        window.ResizeObserver = ResizeObserver as any;
    })
    it("Should render a canvas", async () => {
        let ag: RenderResult<typeof queries, HTMLElement>
        await waitFor(() => {
            ag = render(<AudioGraph freq={500}/>)
        }).then(() => {
  expect(ag.container.querySelector('canvas')?.getContext("2d")?.__getDrawCalls()).toMatchSnapshot()
        })
    })

I'm thinking this has something to do with the replaced ResizeObserver, which is required for chart.js, because there is no actual window and therefor space to render the canvas. Here is my snapshot;

exports[`audiograph Should render a canvas 1`] = `
Array [
  Object {
    "props": Object {
      "height": 0,
      "width": 0,
      "x": 0,
      "y": 0,
    },
    "transform": Array [
      1,
      0,
      0,
      1,
      0,
      0,
    ],
    "type": "clearRect",
  },
  Object {
    "props": Object {
      "height": 0,
      "width": 0,
      "x": 0,
      "y": 0,
    },
    "transform": Array [
      1,
      0,
      0,
      1,
      0,
      0,
    ],
    "type": "clearRect",
  },
]
`;

The documentation shows other methods of getting html out of a canvas but they also return nothing of much use.

What strategy should I use to test that my component is doing what I expect it to?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!