我尝试使用React Testing Library在测试用例中添加useState,但它对我不起作用。我的代码如下。取决于将呈现的isLoading组件。如何在React测试用例中添加isLoading状态?我想在我的测试中将isLoading作为初始状态添加为false。
edit-inspection.tsx
 const [isLoading, setIsLoading] = useState(false);
 useEffect(() => {
    setIsLoading(true);
   }, []);
 const renderComponent = () => {
 <div role="homepagedata">
  </div>;
 }
return isLoading ? <CircularIndeterminate /> : renderComponent();我的测试用例是:
  import EditInspection from '../edit-inspection';
  test('Add new quality inspection record', async () => { 
  render(<EditInspection />);
  expect(screen.getByRole('homepagedata'));
  });显示了这些错误消息
TestingLibraryElementError: Unable to find an accessible element with the role "homepagedata"发布于 2021-10-08 03:56:34
根据您的评论,您的react组件中似乎有很多条件性和逻辑性。以下是一种可能的解决方案,用于测试独立于表示组件的逻辑。
在一个单独的钩子中提取您的所有逻辑,例如useCustomRenderingCondtion,它具有所有的react钩子和您的条件化部分。然后用react-hooks-testing-library测试这个钩子。
工作流程
// container (smart, stateful, logical) component
const EditInspector = () => {
  const isLoading = useCustomRenderingCondtion()
  return <EditInspectorPresentational isLoading={isLoading} />
}
// presenatational (dummy, stateless) component 
const EditInspectorPresentational = ({ isLoading }) => {
   const renderComponent = () => {
     return <div role="homepagedata"></div>
  }
   
  return isLoading ? <CircularIndeterminate /> : renderComponent();
}使用带有React测试库或任何其他功能的react-hooks-testing-library.
useCustomRenderingCondtion。https://stackoverflow.com/questions/69438206
复制相似问题