对于我的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()但是,我一直收到错误"ReferenceError: TextEncoder未定义“。有人能帮忙吗?

请注意
jest-environment-jsdom作为testEnvironment,因为我有react组件,我也在测试此外,如许多条款所述,添加以下内容不起作用:
import { TextEncoder, TextDecoder } from 'util'
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder发布于 2022-07-13 08:06:08
关键是使用require而不是import。在启用fetch模拟之前,必须先设置全局变量。
//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: {}
}))https://stackoverflow.com/questions/72958952
复制相似问题