react-plotly.js icon indicating copy to clipboard operation
react-plotly.js copied to clipboard

How to test React components developed using React-Plotly

Open aditya1 opened this issue 5 years ago • 4 comments

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?

aditya1 avatar Apr 07 '20 14:04 aditya1

Any update on this?

AdnanBoota avatar Sep 18 '20 13:09 AdnanBoota

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

fredrivett avatar Jan 19 '23 10:01 fredrivett

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

scottquested avatar Jan 20 '23 19:01 scottquested