首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Next.js jest-fetch-模拟给出了TextDecoder的错误

Next.js jest-fetch-模拟给出了TextDecoder的错误
EN

Stack Overflow用户
提问于 2022-07-12 22:19:16
回答 1查看 209关注 0票数 0

对于我的Next.JS,我有以下设置

jest.config.js

代码语言:javascript
复制
/* 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

代码语言:javascript
复制
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组件,我也在测试

此外,如许多条款所述,添加以下内容不起作用:

代码语言:javascript
复制
import { TextEncoder, TextDecoder } from 'util'
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
EN

回答 1

Stack Overflow用户

发布于 2022-07-13 08:06:08

关键是使用require而不是import。在启用fetch模拟之前,必须先设置全局变量。

代码语言:javascript
复制
//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: {}
}))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72958952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档