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 Answers 2

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} />);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This answer helped me solve my problem. Here's the API referece in case anyone else wants to check this out: testing-library.com/docs/react-testing-library/api/#rerender
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.