如何使用反应测试库测试反应组件渲染的道具的价值
How to test the value of the props of react component rendered using react testing library
<Abc>
<Xyz data-testid="comp-xyz" prop1={pqr}/>
</Abc>
如果 Abc 是一个 class 组件,我们正在使用 react 测试库测试 Abc,那么有没有办法测试 prop1 的值?
const {getByTestId} = render(<Abc />)
现在我使用 testId 获取组件 Xyz
getByTestId("comp-xyz")
我可以得到这个组件的道具吗?
getByTestId("comp-xyz").props()
?
没有。 testing-library 的想法是鼓励你测试用户与屏幕的交互。
创建依赖于组件数据的测试,例如 props 和 state,对这种类型的测试没有帮助,
因为用户不直接与道具互动,而是与通过它们呈现的元素互动。
还有一点,依赖于实现细节的测试是脆弱的测试,即,
实现中的任何更改,如果不更改组件的行为,都可能无法通过测试
生成 'false-negative'.
在本文档中 link 他们解释得更好:https://testing-library.com/docs/
这可能对某人有帮助:
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
请注意,文档中不鼓励使用这种方法,但有时您必须做您必须做的事情。
<Abc>
<Xyz data-testid="comp-xyz" prop1={pqr}/>
</Abc>
如果 Abc 是一个 class 组件,我们正在使用 react 测试库测试 Abc,那么有没有办法测试 prop1 的值?
const {getByTestId} = render(<Abc />)
现在我使用 testId 获取组件 Xyz
getByTestId("comp-xyz")
我可以得到这个组件的道具吗?
getByTestId("comp-xyz").props()
?
没有。 testing-library 的想法是鼓励你测试用户与屏幕的交互。 创建依赖于组件数据的测试,例如 props 和 state,对这种类型的测试没有帮助, 因为用户不直接与道具互动,而是与通过它们呈现的元素互动。
还有一点,依赖于实现细节的测试是脆弱的测试,即, 实现中的任何更改,如果不更改组件的行为,都可能无法通过测试 生成 'false-negative'.
在本文档中 link 他们解释得更好:https://testing-library.com/docs/
这可能对某人有帮助:
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
请注意,文档中不鼓励使用这种方法,但有时您必须做您必须做的事情。