Mock mutateAsync in jest
I have this hook that I mock with MSW. The tests for the isolated hook work.
Writing tests for my component has been painful. It seems like I have to mock the entire implementation of
export const useEditUserProfile = () => {
return useMutation({
mutationFn: ({ data }: Payload) =>
request({
url: "user",
body: data,
method: "PATCH",
}),
});
};export const useEditUserProfile = () => {
return useMutation({
mutationFn: ({ data }: Payload) =>
request({
url: "user",
body: data,
method: "PATCH",
}),
});
};Writing tests for my component has been painful. It seems like I have to mock the entire implementation of
mutateAsyncmutateAsync. Is there a better way to do this?export const Profile = () => {
const { mutateAsync: mutateUserProfile } = useEditUserProfile();
const onUpdateUserProfile = useCallback(
async (values: UserProfileForm) => {
await mutateUserProfile(
{ data: values },
{
onSuccess: res => {
console.log("res :>> ", res);
const currentUserData = user();
const updatedUserData = {
...currentUserData,
first_name: res.first_name,
last_name: res.last_name,
email: res.email,
};
setUser(updatedUserData);
setAlert({
message: "User profile updated!",
type: "success",
});
},
onError: () => {
setAlert({
message: "Uh-oh! Something went wrong!",
type: "error",
});
},
},
);
},
[mutateUserProfile, setAlert],
);export const Profile = () => {
const { mutateAsync: mutateUserProfile } = useEditUserProfile();
const onUpdateUserProfile = useCallback(
async (values: UserProfileForm) => {
await mutateUserProfile(
{ data: values },
{
onSuccess: res => {
console.log("res :>> ", res);
const currentUserData = user();
const updatedUserData = {
...currentUserData,
first_name: res.first_name,
last_name: res.last_name,
email: res.email,
};
setUser(updatedUserData);
setAlert({
message: "User profile updated!",
type: "success",
});
},
onError: () => {
setAlert({
message: "Uh-oh! Something went wrong!",
type: "error",
});
},
},
);
},
[mutateUserProfile, setAlert],
);