Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'body used already for' error when mocking node fetch?

I'm trying to mock node-fetch with jest for my azure functions. In the test I have the following:

index.test.ts

jest.mock("node-fetch");
import fetch from "node-fetch";
const {Response} = jest.requireActual("node-fetch");

// Setup code here...

const expectedResult: User = {
        user_id: "1",
        email: "[email protected]",
        name: "testUser",
        nickname: "test",
        picture: "pic",
        app_metadata: {
            email: "[email protected]"
        }
    };
    (fetch as jest.MockedFunction<typeof fetch>).mockReturnValue(new Response(JSON.stringify(expectedResult)));

When I call it I'm doing the following:

index.ts


const options = {
                method: 'PATCH',
                headers: { "Content-Type": 'application/json', authorization: `Bearer ${accessToken}`},
                body: body
            };

const userResponse = await fetch(usersEndpoint, options);
const jsonResult = await userResponse.json();
context.res = {
                body: jsonResult
            };

When it hits the "await userResponse.json()" I get "body used already for" error. I have another test that is set up in a similar manner which works so I'm not sure why it's saying the body is used up from the await fetch call. Any help would be appreciated.

like image 428
avenmia Avatar asked May 27 '26 01:05

avenmia


1 Answers

Response object is supposed to be used once per request while mocked fetch returns the same object for multiple requests. Also, it should return a promise of a response, not a response itself.

A correct way to mock it is:

fetch.mockImplementation(() => Promise.resolve(
  new Response(JSON.stringify(expectedResult))
));

It's unnecessary to use Response and follow the restrictions it imposes, especially since there's no native Response in Node.

It can be:

fetch.mockResolvedValue({
  json: jest.fn(() => expectedResult)
});
like image 54
Estus Flask Avatar answered May 28 '26 15:05

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!