简体   繁体   中英

How to test a memoized component's callback using React Testing Library?

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 rtl 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} />);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM