plotly / react-plotly.js

A plotly.js React component from Plotly 📈
MIT License
1.02k stars 136 forks source link

How to test React components developed using React-Plotly #176

Open aditya1 opened 4 years ago

aditya1 commented 4 years ago

Hello,

My team is developing an analytics app using React. We're using react-plotly to generate charts in our app. My question is what is the recommended way to test these components? In our old App, we were downloading the image of the plot using plotly. Save that to our Repo. The test used to generate the image of the plot. Compare the saved image with image generated by the chart. What is the recommended way of testing? Can anyone point to the tests they're writing?

AdnanBoota commented 4 years ago

Any update on this?

fredrivett commented 1 year ago

I'm also in the camp of wanting to test a react component that contains a plot from react-plotly.js.

The latest react testing best practices lean towards integration tests over unit tests where possible, but the only way I've managed to get testing working with react-plotly.js is to mock it and test what's being passed, as without that it fails to render on the server side with the error:

TypeError: window.URL.createObjectURL is not a function

  1 | import React from "react";
  2 |
> 3 | import ReactPlotly from "react-plotly.js";

For those wanting to know my setup (which isn't ideal, as I'd rather test the UI output not the props but is the best I've got so far), here it is (my component that wraps react-plotly.js is called Plot):

import React from "react";

import ReactPlotly from "react-plotly.js";

import Plot from "components/Plot";

// mock the react-plotly.js library, which fails to run server side
jest.mock("react-plotly.js", () => ({
  __esModule: true,
  default: jest.fn(() => <div />),
}));

describe("Plot component", () => {
  it("sets the layout as expected", () => {
    // create a layout with margins set
    const expectedLayout = {
      margin: {
        t: 10,
        b: 20,
        r: 30,
        l: 40,
      },
    };

    // render `Plot`
    render(<Plot data={[]} layout={expectedLayout} />);

    // get the layout passed to ReactPlotly mock
    const mockedReactPlotly = jest.mocked(ReactPlotly);
    // rename `layout` to `observedLayout` for clarity
    const { layout: observedLayout } = mockedReactPlotly.mock.calls[0][0];

    // check that the margin was set as passed and hasn't been overwritten
    expect(observedLayout.margin).toEqual(layout.margin);
  });
});

I would much rather test the UI, does anyone know if there's a way to get react-plotly.js to render server side so the UI can be tested? 🤔

scottquested commented 1 year ago

I would also be very interested in how we can test this

kumargauravin commented 1 month ago

not able to test graph svg generation using react-plotly in jest, snapshot never has SVG generated is this issue same? any pointers. Using React, Nextjs