lquixada / cross-fetch

Universal WHATWG Fetch API for Node, Browsers and React Native.
MIT License
1.66k stars 102 forks source link

URL object doesn't work when running test with Jest for React Native app #145

Closed firasrg closed 1 year ago

firasrg commented 1 year ago

Hello !

While I'm trying to create some tests ๐Ÿงช to my React Native app, so I use Jest in order to do that.

And inside my setupTest.js file I have the following:

const { AbortController } = require('abortcontroller-polyfill/dist/cjs-ponyfill');
import { fetch, Headers, Request, Response } from 'cross-fetch';
import { server } from "@app/tests/mock-server";

global.fetch = fetch;
global.Headers = Headers;
global.Request = Request;
global.Response = Response;
global.AbortController = AbortController;

// Enable the mocking in tests.
beforeAll(() => {server.listen()})

// Reset any runtime handlers tests may use.
afterEach(() => {server.resetHandlers()})

// Clean up once the tests are done. 
afterAll(() => {server.close()})

Note: I use cross-fetch latest version (3.1.5), and Redux RTKQ to manage API calls. When I run the app, the URL object works fine, the issues appears only while testing. ๐Ÿคจ

This is the error I'm getting from redux-toolkit-query:

console.error
An unhandled error occurred processing a request for the endpoint "getItems".
In the case of an unhandled error, no tags will be "provided" or "invalidated". **TypeError: Invalid URL**

๐Ÿ‘‰ The problem is with the URL object. This is how I use the it in my code :

export const apiInstance = MyAPi.injectEndpoints({
    endpoints: (builder) => ({
        getItems: builder.query<IItemsDefinition,IApiItemsDefinitionParams>({
            query: (params: IApiItemsDefinitionParams) => {

                const { currentCount } = params;

                const url: URL = new URL('/items/getAll');

                url.searchParams.append("indexFrom", String(currentCount));
                url.searchParams.append("indexTo", String(currentCount + 5 ));

                return String(url);
            }
        })
    }),
})

I, absolutely, need to solve this issue as its blocking me to finish an important work.

Please help ๐Ÿ™.

firasrg commented 1 year ago

Hi again ๐Ÿ˜… I just figured that the issue I'm facing doesn't have any link to cross-fetch.

The problem was with the declaration of the URL object in code:

Before:

const url: URL = new URL('/items/getAll');

After:

const url: URL = new URL('/items/getAll', "https://api-hostname" );

Now it works after ading the base path following the official docs