【问题标题】:How to write a test for conditional rendering component depended on useState hook in React?如何编写依赖于 React 中 useState 钩子的条件渲染组件的测试?
【发布时间】:2019-12-28 14:20:50
【问题描述】:

我正在尝试为我的功能组件编写测试,但不明白如何将 isRoomsLoaded 模拟为 true,因此我可以正确测试我的 UI。我需要如何模拟以及模拟什么?

import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchRooms } from '../../store/roomsStore';  // Action creator


// Rooms component
export default ({ match, location, history }) => {
    const roomsStore = useSelector(state => state.rooms);
    const dispatch = useDispatch();
    const [isRoomsLoaded, setRoomsLoaded] = useState(false);

    useEffect(() => {
        const asyncDispatch = async () => {
            await dispatch(fetchRooms());
            setRoomsLoaded(true);  // When data have been fetched -> render UI
        };
        asyncDispatch();
    }, [dispatch]);

    return isRoomsLoaded
        ? <RoomsList />  // Abstraction for UI that I want to test
        : <LoadingSpinner />;

};

【问题讨论】:

    标签: reactjs testing react-redux react-hooks conditional-rendering


    【解决方案1】:

    如果您愿意,您可以完全模拟 useState 以仅返回 true 或 false,通过执行以下操作来获得您想要的任何结果。

    const mockSetState = jest.fn();
    
    jest.mock('react', () => ({
      ...jest.requireActual('react'),
      useState: value => [true, mockSetState],
    }));
    

    通过这样做,您可以有效地模拟 react,使用 react,除了 useState,它有点 hacky,但它会起作用。

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 2016-06-06
      • 2019-07-08
      • 2020-01-26
      • 2020-10-29
      • 2020-06-03
      • 1970-01-01
      • 2021-01-21
      • 2019-10-04
      相关资源
      最近更新 更多