我正在尝试为我的功能组件编写测试,但不了解如何将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 />;
};
答案 0 :(得分:0)
如果愿意,可以通过以下操作使模拟useState
完全返回true或false,以获得所需的结果。
const mockSetState = jest.fn();
jest.mock('react', () => ({
...jest.requireActual('react'),
useState: value => [true, mockSetState],
}));
通过这样做,您可以有效地模拟react,react,除了useState之外,它有点hacky,但是可以使用。