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)
fetch
directly – Whiten