[英]How to test a memoized component's callback using React Testing Library?
I'm using React Testing Library with Jest to test my components.我正在使用带有 Jest 的 React 测试库来测试我的组件。 One of the components renders a table with data so I decided to use React.memo as suggested by the table library's author.
其中一个组件使用数据呈现表格,因此我决定按照表格库作者的建议使用 React.memo。 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:但是当我看到测试覆盖率时,我的测试没有覆盖 memo() 回调:
(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.来自 rtl 的
render
function 返回一个 object 并带有重新rerender
function ,您可以使用它来重新渲染带有更新的道具的组件。
const { rerender } = render(<MemoizedComponent data={someData} />);
rerender(<MemoizedComponent data={someOtherData} />);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.