reactjs - 来自父组件的子组件中的检查元素的反应测试库
问题描述
我无法使用反应测试库检查子组件中是否存在元素。
父组件如下
这是子组件的条件渲染取决于位置数组的长度。如果数组长度大于零,则呈现子组件,否则为 null。我想<p>
通过其角色检查子组件中标签的存在。
import ChildComponent from './ChildComponent';
const locationResponse = [
{
id: 1,
locationName: 'On Truck',
locationDesc: 'On Truck Carrier goods',
},
{
id: 2,
locationName: 'In Warehouse',
locationDesc: 'In Warehouse',
},
];
const ParentComponent = () =>
{
const [location, setLocation] = useState(locationResponse);
return (<>
{location.length >0 ?
<ChildComponent/> : null
}
</>
);
}
子组件如下
这是子组件的条件渲染取决于位置数组的长度。如果数组长度大于零,则呈现子组件,否则为 null 。我想<p>
通过其角色检查子组件中标签的存在。
const ChildComponent = () =>
{
return (<>
<p role = "datashow">Child element</p>
</>
);
}
我的测试用例如下
import ParentComponent from './ParentComponent';
test('Clicking go button purchase order list', async () => {
render(<ParentComponent />);
expect(screen.getByRole('datashow'));
});
运行测试用例后出现这些错误。
TestingLibraryElementError:无法找到角色为“datashow”的可访问元素
任何人都可以帮助解决这些问题。
解决方案
正如错误所暗示的,datashow
不是一个有效的角色。一个有效的可访问角色的示例是input
、button
等heading
。由于<p>
没有真正的作用,我建议getByText
改用:
test('Clicking go button purchase order list', async () => {
render(<ParentComponent />);
expect(screen.getByText('Child element').toBeInTheDocument());
});
推荐阅读
- sql - 如何在 DolphinDB 中合并两列不同的时间数据类型?
- c# - 如何在 deps.json 文件中永久设置程序集的自定义运行时路径?
- excel - 使用vba登录
- excel - 是否有条件因素来检查带有字母的文件名然后执行代码?
- python - 如何将多列转置为多行但使用 Pandas 保留主键
- reactjs - reactjs中所有页面的元标记
- angular - 无法使用 localStorage 或 sessionStorage 从内部订阅同步到外部订阅
- autohotkey - LButton启动时如何停止AHK循环
- apache - 如何在服务器代码响应客户端时执行 Apache 重定向
- python - 使用 pandas 或 numpy 将不规则列数据读入 python 3.X