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

问题描述

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

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

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

解决方法

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

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