#Type error request.formData is not a function when testing actions in react router dom 6.4

1 messages · Page 1 of 1 (latest)

foggy nexus
#

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+?

foggy nexus
#

Any pointers on this anyone?

flat rune
# foggy nexus Any pointers on this anyone?

I think I remember seeing a similar issue to this, and the answer was the mock used for Request objects was incorrect, that being said It's also incorrect to provide options for Content-Type application/json. You should use application/x-www-form-urlencoded or multipart/form-data.

As for your main question, I think the solution is:
I upgraded to node18 and removed fetch polyfill, it resolved this.