0

I have the following setup for my Next.JS

jest.config.js

/* eslint-disable @typescript-eslint/no-var-requires */
// jest.config.js
const nextJest = require('next/jest')

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
const customJestConfig = {
  // Add more setup options before each test is run
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  moduleDirectories: ['<rootDir>/node_modules', '<rootDir>/src', '<rootDir>/pages'],
  testEnvironment: 'jest-environment-jsdom',
  testPathIgnorePatterns: [
    '<rootDir>/.next/',
    '<rootDir>/node_modules/',
    '<rootDir>/coverage',
    '<rootDir>/dist'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1'
  },
  resolver: '<rootDir>/.jest/resolver.js'
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)

jest.setup.ts

import '@testing-library/jest-dom'
import '@testing-library/jest-dom/extend-expect'
import fetchMock from 'jest-fetch-mock'

jest.mock('next/config', () => () => ({
  publicRuntimeConfig: {}
}))

fetchMock.enableMocks()

However I keep getting the error "ReferenceError: TextEncoder is not defined". Can anyone help

enter image description here

Please note

  • I need to use jest-environment-jsdom as testEnvironment as I do have react components I am also testing

Also adding the following did not work as mentioned from many articles:

import { TextEncoder, TextDecoder } from 'util'
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
rottitime
  • 1,653
  • 17
  • 29

1 Answers1

0

The key is to use require instead of import. Important to set the global variables first before enabling the fetch mocks.

//jest.setup.ts

import '@testing-library/jest-dom'
import '@testing-library/jest-dom/extend-expect'
import { TextDecoder, TextEncoder } from 'util'
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder

require('jest-fetch-mock').enableMocks()

jest.mock('next/config', () => () => ({
  publicRuntimeConfig: {}
}))
rottitime
  • 1,653
  • 17
  • 29