rottitime
rottitime

Reputation: 2481

Next.js jest-fetch-mock gives error of TextDecoder

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

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

import { TextEncoder, TextDecoder } from 'util'
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder

Upvotes: 0

Views: 967

Answers (1)

rottitime
rottitime

Reputation: 2481

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: {}
}))

Upvotes: 0

Related Questions