recharts: ResponsiveContainer cannot be rendered and hence cannot be tested using react testing library
- I have searched the issues of this repository and believe that this is not a duplicate.
Reproduction link
Steps to reproduce
- Use ResponsiveContainer to render a chart
- Render the chart component with react testing library
What is expected?
The chart should get rendered
What is actually happening?
<div class="recharts-responsive-container makeStyles-chart-21" style="width: 100%; height: 300px;">
<div style="position: absolute; width: 0px; height: 0px; visibility: hidden; display: none;"/>
</div>
The chart is hidden with 0 height and width. No dom nodes are created for the chart.
| Environment | Info |
|---|---|
| Recharts | v1.8.5 |
| React | 16.13.0 |
| System | macOS Mojave 10.14.6 |
| Browser | React testing library |
The chart is rendered while testing if ResponsiveContainer is replaced with a div.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 16
You’re a life-saver, @krzysu! This was making me crazy. The only thing I’ll add is that I had to return all the other recharts components as-is with spread syntax on the original module.
Thanks again!
This solutions worked perfectly fine for me:
<div>element with fixedwidth;warningmessage you get when you try to useOriginalRechartsModule.ResponsiveContainer;you mock ResponsiveContainer in your test, something like below:
Setting the aspect and a fixed width (or height) worked for me to make the warning disappear, i.e.
Just another dirty hack, but it works at least for me.
I was previously using this work-around inspired by @krzysu 's comment
and it worked great, but I also ended up with a bunch of warnings in the console log when running tests…
I’m now using a manual mock in Jest to mock the recharts module that removes the
ResponsiveContainerwhen testing and just renders the child component (which is one of the charts e.g.BarChart,LineChart, etc.) with a fixed width (height is already fixed in my usages), so no more warnings in the console and the chart is rendered in the DOM for testing.file: /__mocks__/recharts.js
Oh, and unfortunately, the method described here wouldn’t work for me since I’m not testing my chart directly but testing at the app/page level and don’t want to have to pass a width prop down multiple component levels to get to my chart.
Alternatively, you can set width as a prop on your chart component, and pass that value to ResponsiveContainer’s width property. Pass “100%” (or whatever percent) to the width prop regularly, and pass it a fixed value, like 1, in your test.
The div solution referenced above does not work for me.