1

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!

2 Answers2

4

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} />);
PaulMest
  • 12,925
  • 7
  • 53
  • 50
Juzer Zarif
  • 346
  • 2
  • 6
  • Thank you! This answer helped me solve my problem. Here's the API referece in case anyone else wants to check this out: https://testing-library.com/docs/react-testing-library/api/#rerender – Breno Baptista Dec 26 '20 at 04:25
1

For anyone wondering, in Jest/Enzyme you can do this with setProps(), which will force a rerender/evaluation of the memo's 'shouldUpdate' condition, aka callback.