'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source