【问题标题】:How to render a conditional component in a Test file? React Testing Library如何在测试文件中呈现条件组件?反应测试库
【发布时间】:2021-06-23 06:40:40
【问题描述】:

我有一个 React 组件,直到 fetchUser 状态不是 loading 时才会呈现。我的测试失败,因为该组件没有第一次呈现,因此找不到page loaded 文本。如何在我的测试中模拟我的 const [fetchStatusLoading, setFetchStatusLoading] = useState(false),以便呈现页面而不是 loading 文本?

const fetchUser = useSelector((state) => (state.fetchUser));

const [fetchStatusLoading, setFetchStatusLoading] = useState(true);

useEffect(() => {
   setFetchStatusLoading(fetchUser .status === 'loading');
}, [fetchStatusLoading, fetch.status]);

useEffect(() => {
        // this is a redux thunk dispatch that sets fetch.status to loading/succeeded 
        dispatch(fetchAPI({ username })); 
}, []);

if(fetchStatusLoading) return 'loading..'; 
return (<>page loaded</>) 

// test case fails 

  expect(getByText('page loaded')).toBeInTheDocument();

【问题讨论】:

  • 您是否尝试将您的expect 包装在waitFor 块中?

标签: javascript reactjs unit-testing jestjs react-testing-library


【解决方案1】:

如果您能够模拟加载状态,那么您将只测试“渲染”部分的代码,而不是您应该测试的所有组件逻辑,因为这就是测试库要大放异彩的方式。

如果这只是一个异步问题,你可以这样做:

test('test page loaded', async () => {
  render(<MyComponent />);

  expect(await screen.findByText('page loaded')).toBeInTheDocument();
});

但是您的组件似乎包含一个 API 请求,因此如果该组件接受一个函数,您可以模拟它并返回值,或者您可以模拟 fetch。 Here are some reasons why you should not do that.

使用nockmock-service-worker,您可以拥有一个响应您的API 请求的假服务器,因此无需模拟任何内部状态即可运行您的组件测试。

测试库只是在类似浏览器的环境中呈现组件,不提供 API 来修改任何道具或状态。它是为此目的而创建的,与 Enzyme 相反,它提供了一个 API 来访问组件的 props 和 state。

看看这个类似的问题:check state of a component using react testing library

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 1970-01-01
    • 2021-05-16
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多