I'm using React Testing Library with Jest to test my components. One of the components renders a table with data so I decided to use React.memo as suggested by the table library's author. I'm using it like this:
import React, { memo } from 'react'
const MemoizedComponent = memo(({ data }) => {
// Component logic
return (
<>
// Component UI
</>
)
}, (prevProps, nextProps) => {
if (JSON.stringify(prevProps) !== JSON.stringify(nextProps)) {
return false
}
return true
})
export default MemoizedComponent
But when I see the test coverage the memo() callback isn't being covered by my tests:
(prevProps, nextProps) => {
if (JSON.stringify(prevProps) !== JSON.stringify(nextProps)) {
return false
}
return true
}
Is there a way to change the props after the render so I can finish testing this memoized component? Thank you!
The render
function from React Testing Library returns an object with a rerender
function that you can use to rerender your component with updated props.
const { rerender } = render(<MemoizedComponent data={someData} />);
rerender(<MemoizedComponent data={someOtherData} />);