如何编写依赖于React中useState挂钩的条件渲染组件的测试?

时间:2019-08-23 09:17:14

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

我正在尝试为我的功能组件编写测试,但不了解如何将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 />;

};

1 个答案:

答案 0 :(得分:0)

如果愿意,可以通过以下操作使模拟useState完全返回true或false,以获得所需的结果。

const mockSetState = jest.fn();

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

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