如何修复ReferenceError:Next.js项目的jest测试中没有定义TextEncoder?

vulvrdjw  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(277)

我有一个单元测试,正在检查页面上是否呈现了特定的项目。此单元测试失败,我得到以下错误:

Test suite failed to run

    ReferenceError: TextEncoder is not defined

       6 | import { unformatPhoneNumber } from '../../../utils/formatter';
       7 | import ReactHtmlParser from 'react-html-parser';
    >  8 | import DOMPurify from 'isomorphic-dompurify';

字符串
基于这个主题的其他stackoverflow问题,我在项目的根目录中添加了一个jest.setup.js文件和一个jest.setup.js文件。
这是我从Next.js示例存储库https://github.com/vercel/next.js/tree/canary/examples/with-jest-babel中复制的jest.js.js中的内容

// You can learn more about each option below in the Jest docs: https://jestjs.io/docs/configuration.

module.exports = {
  collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.d.ts', '!**/node_modules/**'],
  moduleNameMapper: {
    // Handle CSS imports (with CSS modules)
    // https://jestjs.io/docs/webpack#mocking-css-modules
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',

    // Handle CSS imports (without CSS modules)
    '^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',

    // Handle image imports
    // https://jestjs.io/docs/webpack#handling-static-assets
    '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': `<rootDir>/__mocks__/fileMock.js`,

    // Handle module aliases
    '^@/components/(.*)$': '<rootDir>/components/$1',

    '^@/pages/(.*)$': '<rootDir>/pages/$1',
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  transform: {
    // Use babel-jest to transpile tests with the next/babel preset
    // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
    '^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
  },
  transformIgnorePatterns: ['/node_modules/', '^.+\\.module\\.(css|sass|scss)$'],
  testEnvironment: 'jest-environment-jsdom',
};


这就是我在jest.setup.js中的内容,

// Optional: configure or set up a testing framework before each test.
// If you delete this file, remove `setupFilesAfterEnv` from `jest.config.js`

// Used for __tests__/testing-library.js
// Learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;


在添加了这个之后,我仍然得到同样的错误。我使用的是node v16.18.0。
这是一个Nextjs,Typescript,React应用程序。我还有一个jest-config.d.ts文件,其中包含以下内容:

declare const root: any;
export { root as rootDir };
export declare const setupFilesAfterEnv: string['<rootDir>/jest.setup.js'];
export declare const testMatch: string[];
export declare const testPathIgnorePatterns: string[];
export declare const coveragePathIgnorePatterns: string[];
export declare const coverageDirectory: string;
//# sourceMappingURL=jest-config.d.ts.map


我不知道我是否需要在这个文件中添加任何东西。

yftpprvb

yftpprvb1#

您遇到的错误ReferenceError:TextEncoder is not defined可能是由于默认情况下TextEncoder和TextDecoder全局对象在Node.js环境中不可用。
要解决此问题,您可以使用文本编码包,该包为Node.js环境中的TextEncoder和TextDecoder提供polyfill。
以下是解决此问题的步骤:
安装文本编码包:

npm install text-encoding

Update your jest.setup.js file to include the polyfill:
// jest.setup.js

// Used for __tests__/testing-library.js
// Learn`enter code here` more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';

// Polyfill for TextEncoder and TextDecoder in Node.js
import { TextEncoder, TextDecoder } from 'util';
if (typeof global.TextEncoder === 'undefined') {
  global.TextEncoder = TextEncoder;
}
if (typeof global.TextDecoder === 'undefined') {
  global.TextDecoder = TextDecoder;
}

字符串
只有在TextEncoder和TextDecoder尚未定义时,才会有条件地对其进行多边形填充。
再次运行测试:

npm test


这应该可以解决Jest测试中的ReferenceError:TextEncoder is not defined问题。

相关问题