【问题标题】:How to test the value of the props of react component rendered using react testing library如何测试使用反应测试库渲染的反应组件的道具的价值
【发布时间】:2021-04-07 05:53:42
【问题描述】:
<Abc> 
  <Xyz data-testid="comp-xyz" prop1={pqr}/>
</Abc>

这里如果 Abc 是一个类组件,并且我们正在使用 react 测试库测试 Abc,那么有没有办法测试 prop1 的值?

const {getByTestId} = render(<Abc />)

现在我使用 testId 获取组件 Xyz getByTestId("comp-xyz")

我可以像这样得到这个组件的道具吗? getByTestId("comp-xyz").props()?

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    没有。 testing-library 的想法是鼓励你测试用户与屏幕的交互。 创建依赖于组件数据的测试,例如 props 和 state,对这种类型的测试没有帮助, 因为用户不直接与道具交互,而是与通过它们渲染的元素进行交互。

    另外一点是,依赖于实现细节的测试是脆弱的测试,也就是说, 任何不改变组件行为的实现更改都可能使其测试失败 产生“假阴性”。

    在这个文档链接中,他们解释得更好:https://testing-library.com/docs/

    【讨论】:

    • 来自文档...测试库鼓励您避免测试实现细节,例如您正在测试的组件的内部结构(尽管它仍然是可能的) - 请参阅下面的答案以了解其可能性跨度>
    【解决方案2】:

    这可能对某人有帮助:

    const { fixture } = await render(AppComponent)
    const componentInstance = fixture.componentInstance as AppComponent
    expect(componentInstance.prop).toBe(true)
    

    https://testing-library.com/docs/angular-testing-library/api/#fixture

    请注意,文档中不鼓励这种方法,但有时你必须做你必须做的事情。

    【讨论】:

      猜你喜欢
      • 2019-12-25
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 2020-09-16
      • 2020-09-28
      • 1970-01-01
      相关资源
      最近更新 更多