首页 > 解决方案 > 来自父组件的子组件中的检查元素的反应测试库

问题描述

我无法使用反应测试库检查子组件中是否存在元素。

父组件如下

这是子组件的条件渲染取决于位置数组的长度。如果数组长度大于零,则呈现子组件,否则为 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”的可访问元素

任何人都可以帮助解决这些问题。

标签: reactjsreact-testing-library

解决方案


正如错误所暗示的,datashow不是一个有效的角色。一个有效的可访问角色的示例是inputbuttonheading。由于<p>没有真正的作用,我建议getByText改用:

test('Clicking go button purchase order list', async () => {
  render(<ParentComponent />);
  expect(screen.getByText('Child element').toBeInTheDocument());
}); 

推荐阅读