While I was playing around with recharts
, I was curious about how to write tests with charts.
Because everything is rendered with SVGs and texts, I thought it might be easy to test with by querying for rendered elements.
This component code:
Test code:
Even though this test code looks promising because I even used querySelector
in my test to drill down to find what I want…
But tests fail to find the elements I need. While debugging, I realized NO SVGs were rendered. But my charts in the above screenshot look just fine. Where did the SVGs go?
Problem
The problem was that ResponsiveContainer
needs fixed width and height when rendering from the tests. In the implementation, it makes sense to use 100% width rather than a fixed width.
Solution
Add this at the top of the test file to override the width and height of the ResponsiveContainer
invoked from the implementation.
jest.mock('recharts', () => {
const OriginalModule = jest.requireActual('recharts')
return {
...OriginalModule,
ResponsiveContainer: ({ children }) => (
<OriginalModule.ResponsiveContainer width={800} height={800}>
{children}
</OriginalModule.ResponsiveContainer>
),
}
})
This will make all tests to pass but will give a console warning…