I have created a component in React, which renders its content from the data obtained in an API. When the data arrives, I feed it into the local state of the component.
From here the component makes use of that state, and uses the data to paint a list.
const UserList = ({ type }) => {
const [users, setUsers] = useState([]);
const [usersByType, setUsersByType] = useState([]);
let update = useSelector((state) => state.update);
const getMaxFiveUsers = (users) => {
return users[type].slice(0, 5);
};
useEffect(() => {
getUsersByType().then((users) => {
setUsers(users);
setUsersByType(getMaxFiveUsers(users));
});
}, [update]);
return (
<div className={usersByType.length ? "userlist" : "hidden"}>
<ul>
{usersByType.map((user, i) => {
return (
<li className="userlist__item" key={i}>
<UserCell username={user} userType={type} users={users} />
</li>
);
})}
</ul>
</div>
);
};
export default UserList;
The problem is that I want to test this component with Jest, and when rendering it, the component has no values in its state and therefore returns an empty list.
Can its status be set when starting the test to introduce some test users and thus render the list?
In your case, you are interested in mocking the dependency that brings the data from the server:
getUsersByType
. To do this you can usejest.mock
and mock the module (Assuming that the function to mock is thedefault export
):In the event that it is not
default export
there are several ways to do it, one of them would be withjest#spyOn
: