Why am I getting "TextEncoder is not defined" in Jest?

Viewed 7093

When testing a function that uses either the TextEncoder or the TextDecoder I get:

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

I am using jsdom, so why is this not working?

3 Answers

While it should be bundled with jsdom, it isn't with jsdom 16. Therefore you can polyfill like so:

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

I received this error as well and am using the standard Next.js jest and react testing library test setup outlined in the docs here: https://nextjs.org/docs/testing#setting-up-jest-with-the-rust-compiler.

In particular, it uses the testEnvironment: 'jest-environment-jsdom' test environment in jest.config.js configuration file.

Unfortunately, importing jsdom in one of my backend api routes (Express routes) broke my tests, giving me the TextEncoder is not defined error.

I was able to fix it by adding the following to the top of the file that housed the broken test:

/**
 * @jest-environment node
 */
// my-broken-node-only-test.js

Read more about this technique via the jest docs.

Lastly, the following issue comment by Jest maintainer Simen helped clarify what was happening in my case: https://github.com/jsdom/jsdom/issues/2524#issuecomment-902027138

Make sure your whatwg-url package has version ^10.0.0 at least

Related