【问题标题】:How to Unit test the rendering of a child component in the parent component using react testing library?如何使用反应测试库对父组件中子组件的渲染进行单元测试?
【发布时间】:2020-09-28 06:08:49
【问题描述】:

我无法在此处发布原始代码,因此我将尝试解释我想要实现的目标。 所以,我的组件显示消息。此消息是在父组件中呈现的子组件的一部分。所以,我想对这个逻辑进行单元测试。但我不知道如何编写单元测试来呈现子组件react 测试库中的组件。示例代码:

function Home(props){
const message=props;
if(message==='warning')
return <Warning display={message}/>

所以我想编写单元测试以使用 react-testing-library 在我的父组件中实现警告组件的呈现。

【问题讨论】:

  • 如果我的回答有帮助或者您需要更多帮助,请告诉我!

标签: reactjs react-testing-library react-test-renderer


【解决方案1】:

我看不到你的代码,所以我有点猜测,但你需要这样的东西:

const props = { message: 'warning'}

const { container, getByText } = render(
    <Home {...props} />,
)

expect(getByText('warning')).toBeInTheDocument()

让我知道这是否有效

【讨论】:

  • 我找不到 toBeInTheDocument() 方法。我错过了什么??
  • 你从react-testing-library导入什么?您需要导入:import { render } from '@testing-library/react' 然后它应该已经在页面上
  • 我已经按照你建议的方式导入了它,但它仍然不在页面中。
  • 我想通了。我需要导入'import '@testing-library/jest-dom/extend-expect'。让我测试一下你的解决方案是否有效。
  • 你现在要导入什么?
猜你喜欢
  • 2021-11-07
  • 2019-12-25
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
  • 2021-04-07
  • 1970-01-01
  • 2020-03-15
相关资源
最近更新 更多