为什么我在 Jest 中收到“TextEncoder 未定义”?

leo*_*ess 43 javascript jsdom jestjs

TextEncoder当测试使用 或的函数时,TextDecoder我得到:

ReferenceError: TextEncoder is not defined
ReferenceError: TextDecoder is not defined
Run Code Online (Sandbox Code Playgroud)

我正在使用jsdom,为什么这不起作用?

leo*_*ess 90

虽然它应该与 jsdom 捆绑在一起,但它不与 jsdom 16 捆绑在一起。因此你可以像这样进行 polyfill:

import { TextEncoder, TextDecoder } from 'util';

Object.assign(global, { TextDecoder, TextEncoder });
Run Code Online (Sandbox Code Playgroud)

您必须将其添加到测试或像setupFile这样的文件中setup.jest.ts

  • 这个应该加到哪里呢?我将其添加到容纳失败测试的文件中,我在 global.TextDecoder Type 'typeof TextDecoder' is not allocate to type '{ new (label?: string | undefined, options?: TextDecoderOptions | undefined): TextDecoder; 下收到此错误 原型:TextDecoder;}' (6认同)
  • @dragonfly02您必须将其添加到测试或[setupFile](https://jestjs.io/docs/configuration#setupfiles-array) (2认同)

Jas*_*CFA 31

我也收到了这个错误,并且正在使用此处文档中概述的标准 Next.js jest 和 React 测试库测试设置:https://nextjs.org/docs/testing#setting-up-jest-with-the-rust -编译器

特别是,它使用配置文件testEnvironment: 'jest-environment-jsdom' 中的测试环境jest.config.js

不幸的是,在我的后端 api 路由(Express 路由)之一中导入 jsdom 破坏了我的测试,给了我错误TextEncoder is not defined

我可以通过将以下内容添加到包含损坏测试的文件顶部来修复它:

/**
 * @jest-environment node
 */
// my-broken-node-only-test.js
Run Code Online (Sandbox Code Playgroud)

通过jest 文档了解有关此技术的更多信息。

最后,Jest 维护者 Simen 的以下问题评论有助于澄清我的案例中发生的情况:https://github.com/jsdom/jsdom/issues/2524#issuecomment-902027138