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

问题描述 投票:0回答:4

当测试使用

TextEncoder
TextDecoder
的函数时,我得到:

ReferenceError: TextEncoder is not defined
ReferenceError: TextDecoder is not defined

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

javascript jestjs jsdom
4个回答
68
投票

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

import { TextEncoder, TextDecoder } from 'util';

Object.assign(global, { TextDecoder, TextEncoder });

23
投票

我也收到了这个错误,并且正在使用文档中概述的标准 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

通过 
the jest docs

阅读有关此技术的更多信息。

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


1
投票
@leonheess 的答案

添加到测试文件的顶部(其中发生错误,导致错误的行之前):

import { TextEncoder, TextDecoder } from 'util' global.TextEncoder = TextEncoder // @ts-expect-error global.TextDecoder = TextDecoder

即使尝试得很好,例如

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

我遇到了类似的错误

Type 'typeof TextDecoder' is missing the following properties from type 'TextDecoder': decode, encoding, fatal, ignoreBOMts(2739)

或与

global.TextDecoder = {prototype: new TextDecoder("utf-8")}

我明白了

Type 'import("util").TextDecoder' is not assignable to type 'TextDecoder'. Types of property 'decode' are incompatible. Type '(input?: ArrayBuffer | ArrayBufferView | null | undefined, options?: { stream?: boolean | undefined; } | undefined) => string' is not assignable to type '(input?: BufferSource | undefined, options?: TextDecodeOptions | undefined) => string'. Types of parameters 'input' and 'input' are incompatible. Type 'BufferSource | undefined' is not assignable to type 'ArrayBuffer | ArrayBufferView | null | undefined'. Type 'ArrayBufferView' is not assignable to type 'ArrayBuffer | ArrayBufferView | null | undefined'. Type 'ArrayBufferView' is missing the following properties from type 'DataView': getFloat32, getFloat64, getInt8, getInt16, and 17 more.

所以最好只分配并忽略不兼容性。

import { TextEncoder, TextDecoder } from 'util' global.TextEncoder = TextEncoder // @ts-expect-error global.TextDecoder = TextDecoder

编辑:

我知道这很丑陋,但没有找到其他方法。


-5
投票
whatwg-url

软件包至少有

^10.0.0
版本
    

© www.soinside.com 2019 - 2024. All rights reserved.