简体   繁体   English

如何使用 React 测试库测试记忆化组件的回调?

[英]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.

相关问题 如何使用 react 测试库 jest 测试下拉组件? - How to test a dropdown component in react using react testing library jest? 如何使用反应测试库测试带有钩子的反应组件 - How to test react component with hooks using react testing library 如何使用反应测试库测试需要钩子的组件? - How to test Component which requires hook using react testing library? 使用 test 和 react-testing-library 测试反应组件 - Test a react component using test and react-testing-library 使用 Redux 和 react-testing-library 测试 React 组件 - Test React Component using Redux and react-testing-library 如何使用反应测试库对父组件中子组件的渲染进行单元测试? - How to Unit test the rendering of a child component in the parent component using react testing library? 如何使用 onClick 函数 Jest/React 测试库测试 React 组件 - How to test react component with onClick function Jest/React testing library 如何使用 React 测试库测试 React 组件是否返回 null 或其子级? - How to test if React component is returning null or its children using React Testing Library? 如何使用反应测试库测试 HOC - How to test HOC using react testing library 如何测试使用反应测试库渲染的反应组件的道具的价值 - How to test the value of the props of react component rendered using react testing library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM