vendredi 23 août 2019

How to write a test for conditional rendering component depended on useState hook in React?

I'm trying to write a test for my functional component, but don't understand how to mock isRoomsLoaded to be true, so I could properly test my UI. How and what do I need to mock?

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 />;

};

Aucun commentaire:

Enregistrer un commentaire