Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetchBaseQuery with jest + msw results in ReferenceError: Request is not defined #2084

Closed
jnachtigall opened this issue Feb 28, 2022 · 5 comments

Comments

@jnachtigall
Copy link

I have seen #1271 (comment) and read through the whole thread. Even with all these workarounds I get:

Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.

followed by:

      An unhandled error occured processing a request for the endpoint "getErrorMessages".
      In the case of an unhandled error, no tags will be "provided" or "invalidated". ReferenceError: Request is not defined
          at /home/jnachtigall/dev/werkzeuge/source/frontend/node_modules/@reduxjs/toolkit/src/query/fetchBaseQuery.ts:235:11
          at step (/home/jnachtigall/dev/werkzeuge/source/frontend/node_modules/@reduxjs/toolkit/dist/query/rtk-query.cjs.development.js:23:23)
          at Object.next (/home/jnachtigall/dev/werkzeuge/source/frontend/node_modules/@reduxjs/toolkit/dist/query/rtk-query.cjs.development.js:4:53)
          at fulfilled (/home/jnachtigall/dev/werkzeuge/source/frontend/node_modules/@reduxjs/toolkit/dist/query/rtk-query.cjs.development.js:95:32)

My code is as follows:

import "whatwg-fetch";
import { rest } from "msw";
import { setupServer } from "msw/node";
import { useEffect } from "react";
import { render } from "@testing-library/react";

....

const testErrorMsgs: ErrorMessagesType = {
	cardinality: {
		forced_empty: "msg0 {0}",
		forced_required: "msg1 {0}",
		range: "msg2 {0} {1} {2}",
		minimum: "msg3 {0} {1}",
	},
};

/**
 * Mock-Server with msw
 * https://testing-library.com/docs/react-testing-library/example-intro
 */
const server = setupServer(
	rest.get("/api/v1/meldungen", async (req, res, ctx) => {
		return res(ctx.json(testErrorMsgs));
	}),
);

beforeAll(() => {
	server.listen();
});

afterAll(() => {
	server.close();
});

afterEach(() => {
	server.resetHandlers();
});

and

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import type ErrorMessagesType from "../types/ErrorMessages";

export const errorMessagesSlice = createApi({
	reducerPath: "errorMessages",
	baseQuery: fetchBaseQuery({ baseUrl: "/api/v1" }),
	endpoints: (builder) => ({
		getErrorMessages: builder.query<ErrorMessagesType, void>({
			query: () => "/meldungen",
		}),
	}),
});

export const { useGetErrorMessagesQuery } = errorMessagesSlice;

Naturally, I would be interested in getting the test to work. More generally, could you maybe provide some documentation on how to setup jest test using RTK Query?

@valkum
Copy link

valkum commented Mar 2, 2022

I believe you need to import the polyfill before the api gets created. Is your import in a setupTests file (jest: setupFilesAfterEnv) or in a local test file?

@jnachtigall
Copy link
Author

Is your import in a setupTests file (jest: setupFilesAfterEnv) or in a local test file?

I tried both. None worked.

@valkum
Copy link

valkum commented Mar 2, 2022

Are you sure you have setupFilesAfterEnv set (if you do not use something like CRA)? I added whatwg-fetch exactly the same way (in our setupTests.js) just yesterday and it works.

Some more information about your setup might be interesting then.

@jnachtigall
Copy link
Author

Yes, the problem was indeed a missing setupFilesAfterEnv in our vite.js setup. Changing in our jest.config.js from

setupFilesAfterEnv: ["@testing-library/jest-dom"],

to

setupFilesAfterEnv: ["@testing-library/jest-dom", "./jest.setup.ts"],

with jest.setup.ts being a simple:

import "whatwg-fetch";

(and previously installing/adding "whatwg-fetch" with npm) makes it work.

So I am closing. Though it would not hurt to add a paragraph somewhre in the official docs adding this (sorry, for having no time to do it myself)

Thank you! Great toolkit!

lucasgarfield added a commit to lucasgarfield/image-builder-frontend that referenced this issue Feb 7, 2023
We are migrating towards using RTK Query for API calls, and using `msw`
to mock APIs in our tests.

RTK Query's `fetchBaseQuery` requires the use of `fetch` and `Request`.

`fetch()` was added to Node in v18, and the ability to use it in
Jest tests was added to Jest in v28. However, it still cannot be used
with a `jsdom` test environment.

Therefore, it is necessary to add a polyfill. There are several
libraries available for this but many others in this situation have had
success using `whatwg-fetch` and so it was selected somewhat
arbitrarily.

It is also important that `whatwg-fetch` is imported before
`fetchBaseQuery` (otherwise, a nuisance console warning will be issued).
To ensure this happens, it is imported in a Jest setup file.

References:
reduxjs/redux-toolkit#2084
reduxjs/redux-toolkit#1271
jestjs/jest#13834
@lucasgarfield
Copy link

Adding a comment to hopefully save anyone who finds this issue while troubleshooting these warnings/errors some time.

(!) at the time of writing this, fetch is not available when using the jsdom environment (!)
see here: jestjs/jest#13834 (comment)

This issue was raised in March 2022. Jest v28 was released in April 2022, after this post. Jest 28 adds support for fetch (which has been available in Node since v18). However, I was still receiving the same warning and error messages that prompted this issue and could not understand why. After some investigation I learned that it was because our project is using jsdom. I implemented the same solution (install whatwg-fetch as a dev dependency and import it in the Jest setup file) and was able to eliminate the errors and warnings.

thedoublejay added a commit to levaintech/sticky that referenced this issue Feb 8, 2023
<!--  Thanks for sending a pull request! -->

#### What this PR does / why we need it:
To prevent fetch warnings on jest:
reduxjs/redux-toolkit#2084
#### Which issue(s) does this PR fixes?:

<!--
(Optional) Automatically closes linked issue when PR is merged.
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->

Fixes #

#### Additional comments?:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants