Next.js Discord

Discord Forum

Testing NextJS 14, Server Actions with jest, throws error fetch is not defined

Unanswered
Cinnamon posted this in #help-forum
Open in Discord
CinnamonOP
I am trying to test my NextJs 14 App with Jest, and I have an issue when trying to test a server action, it throws this error:

   ReferenceError: fetch is not defined                                                                                                                                               
      21 |              key                                                                                                                                                                                                         
      22 |      }).returning('id')                                                                                                                                                                                                  
    > 23 |      revalidateTag(TableNames.productGroups)
         |                   ^
      24 |
      25 |      return createdEntityId;

Which seems to be due to the revalidateTag, but I am not sure how to fix this.

Config
import nextJest from 'next/jest.js'
 
const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})
 
// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
  // Add more setup options before each test is run
    preset: 'ts-jest',
    // transform: {
    //     '^.+\\.tsx?$': 'ts-jest'
    // },
    // globals: {
    //     'ts-jest': {
    //         diagnostics: false
    //     }
    // },
    testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
    setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
    testEnvironment: 'jest-environment-jsdom',
    testPathIgnorePatterns: ['/public/', '/src/assets/'],//['/node_modules/', '/.next/'] is automatically added,
}
 
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)

0 Replies