I have an action function as part of react-router-dom (React router 6.4) which is attached to a route and fetches some data based on certain id. I'm trying to test the action but I get the error -
TypeError: request.formData is not a function
Test for action -
it("should return a success response", async () => {
const mockResponse = {
response: "success",
hasError: false,
status: 200,
contextType: "GET_DATA_FROM_ID"
};
const formData = new FormData();
formData.append("contextType", "GET_DATA_FROM_ID");
const myOptions = {
method: "POST",
headers: {
"Content-Type":"application/json",
},
body: formData
};
let request = new Request(GET_DATA_FROM_ID, myOptions);
const response = await myAction({ request, params: {} });
expect(response).toEqual(mockResponse);
});
});
Code for action -
export const myAction = async ({ request }: Request) => {
try {
const response = await axios.get(`${URL}${id}`, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
withCredentials: false,
});
if (response.status === 200) {
return json({
response: response.data,
isError: false,
status: 200,
contextType,
});
}
} catch (error: any) {
return json({
error,
isError: true,
status: error.status,
contextType,
});
}
}
The same issue occurs if I'm on Node 16 or 18.
What am I missing here? Is there another way to test action functions in react router 6.4+?