首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在React测试库中添加useState

如何在React测试库中添加useState
EN

Stack Overflow用户
提问于 2021-10-04 15:01:18
回答 1查看 237关注 0票数 1

我尝试使用React Testing Library在测试用例中添加useState,但它对我不起作用。我的代码如下。取决于将呈现的isLoading组件。如何在React测试用例中添加isLoading状态?我想在我的测试中将isLoading作为初始状态添加为false。

edit-inspection.tsx

代码语言:javascript
运行
复制
 const [isLoading, setIsLoading] = useState(false);
 useEffect(() => {
    setIsLoading(true);

   }, []);

 const renderComponent = () => {
 <div role="homepagedata">
  </div>;
 }
return isLoading ? <CircularIndeterminate /> : renderComponent();

我的测试用例是:

代码语言:javascript
运行
复制
  import EditInspection from '../edit-inspection';
  test('Add new quality inspection record', async () => { 
  render(<EditInspection />);
  expect(screen.getByRole('homepagedata'));
  });

显示了这些错误消息

代码语言:javascript
运行
复制
TestingLibraryElementError: Unable to find an accessible element with the role "homepagedata"
EN

回答 1

Stack Overflow用户

发布于 2021-10-08 03:56:34

根据您的评论,您的react组件中似乎有很多条件性和逻辑性。以下是一种可能的解决方案,用于测试独立于表示组件的逻辑。

在一个单独的钩子中提取您的所有逻辑,例如useCustomRenderingCondtion,它具有所有的react钩子和您的条件化部分。然后用react-hooks-testing-library测试这个钩子。

工作流程

代码语言:javascript
运行
复制
// 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.

  • Test EditInspectorPresentational进行
  1. 测试useCustomRenderingCondtion
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69438206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档