I have a file with a function like:
export async function loginNextAuth(displayName, password) {
const response = await fetch('/api/auth/callback/credentials')
}
Notice there are no imports, this is a built-in Node.js fetch function in the global namespace. This works fine in Playwright tests and regular code.
For some reason both global and globalThis do not have the fetch property while running in Jest tests. This results in an error from jest saying the fetch variable is undeclared.
The process.version returned in jest tests is the same as the Node version I am using in development.
This is a similar SO question, but there OP is using an external fetch function imported from a module.
Update: Node version is v18.12.1
The error in question:
const response = await fetch("/api/auth/callback/credentials", {
^
ReferenceError: fetch is not defined
at Object.loginNextAuth (web_app/lib/tests/jest/login.js:8:22)
at loginAs (web_app/pages/permissions.jest.js:22:71)
When using Node 18, Jest removes the global reference to fetch.
A work around is to add it to the globals in your jest.config.js file.
globals: {
fetch: global.fetch,
}
A couple of other potential gotchas to bare in mind:
For those still looking for an answer, fetch API is only available in Jest's node test environment in Jest v28+ as pointed out in this comment. To access it you must run your tests in node test environment, which is Jest's default test environment, instead of jsdom. You can either add testEnvironment: "node" to your jest config, or if you want to change it for a specific test file, you can add @jest-environment node in a docblock on top of your test file. See https://jestjs.io/docs/configuration#testenvironment-string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With