wheresrhys / fetch-mock

Mock http requests made using fetch
http://www.wheresrhys.co.uk/fetch-mock/
MIT License
1.29k stars 179 forks source link

FetchMock@12, ReferenceError: Response is not defined #864

Open ShamaGarg opened 2 weeks ago

ShamaGarg commented 2 weeks ago

Node: v20.17.0 NPM: 10.8.2 fetchMock: 12.0.2 webpack: 5.95.0

I am trying to upgrade tests in our project (React) with v12. Made all of the changes as per the new documentation. But now I am starting to get the error: ReferenceError: Response is not defined for all of the tests. This is an example of how a test with new changes look like:

describe(A test using fetchMock', () => {
    beforeEach(() => {
        fetchMock.mockGlobal();
    });

    afterEach(() => {
        fetchMock.clearHistory();
        fetchMock.removeRoutes();
        fetchMock.unmockGlobal();
    });

    it('It should display data for the site', async () => {
        fetchMock.get('api/random/sites', [{code: 'TEST', name: 'TestName'},{code: 'TEST1', name: 'TestName1'}]);
        const { findByTestId} = setup();
        await act(async () => fetchMock.callHistory.flush(true));

        const container = await findByTestId('data-container');
        expect(container).toBeInTheDocument();

        expect(fetchMock.callHistory.called('api/dashboard/emergency/sites')).toBeTruthy();
    });
});
pendingPromises: [
        Promise {
          <rejected> ReferenceError: Response is not defined
              at Router.generateResponse node_modules\fetch-mock\dist\cjs\Router.js:137:38)
              at node_modules\fetch-mock\dist\cjs\Router.js:117:74
        }
      ],

I am not sure if my test still missing something that is needed for v12, I am happy to provide additional information if needed.

Thanks in advance!

wheresrhys commented 2 weeks ago

This sounds like something related to your specific test runner's environment. Are you able to create a repo with a reduced test case that includes exactly how you're configuring webpack, react etc. Once I have that I can investigate

ShamaGarg commented 1 week ago

It is a bit difficult to create a repo. If this helps, when I added fetch-ponyfill in jestSetup.ts (which is my setupFilesAfterEnv in jest config) and the following code in the same file:

const ponyfillFetch = fetchPonyfill();
if (!globalThis.fetch) {
    globalThis.fetch = ponyfillFetch.fetch;
    globalThis.Headers = ponyfillFetch.Headers;
    globalThis.Request = ponyfillFetch.Request;
    globalThis.Response = ponyfillFetch.Response;
}

Error is gone, but then test succeeds only when I mock response like this:

fetchMock.get('api/random/sites', new Response(JSON.stringify([{code: 'TEST', name: 'TestName'},{code: 'TEST1', name: 'TestName1'}])));

Additional Information: testEnvironment: 'jsdom',

And a snippet of polyfills used in webpack:

const polyfills = [
    'core-js/stable',
    'regenerator-runtime/runtime',
    'time-input-polyfill',
    'url-search-params-polyfill',
    'whatwg-fetch',
    'abortcontroller-polyfill'
];

export const baseOptions = {
    entry: {
        app: [...polyfills, './index.tsx'],
    },
    exclude: [
        /node_modules/,
        /polyfills/
    ],
    plugins: {},
    sourceMap: true,
};
wheresrhys commented 1 week ago

Sorry, I'll only look at it if you create a repo that demonstrates the failure. In my experience, discussing things without an example I can actually run just takes a lot longer, and often I am unable to recreate the issue and debug as it relies on something that has been left out of the description provided in the issue.