Skip to content
Latchkey

Jest "ReferenceError: TextEncoder is not defined" (jsdom)

Code under test referenced TextEncoder (or TextDecoder, crypto.subtle, ResizeObserver), a Web API the jsdom environment does not provide. Referencing it throws unless you polyfill it in setup.

What this error means

A test throws ReferenceError: TextEncoder is not defined, often from a dependency that encodes bytes (uuid, a crypto lib). The same code runs in a real browser; jsdom simply omits the global.

jest
ReferenceError: TextEncoder is not defined

   6 | import { v4 as uuid } from 'uuid';
   7 |
 > 8 | const enc = new TextEncoder();
     |             ^

Common causes

jsdom does not implement the API

jsdom omits some Web APIs (TextEncoder, crypto.subtle, ResizeObserver, fetch on older setups). Referencing them throws a ReferenceError.

Wrong environment for the code

Under the default node environment there is no window/document; under jsdom some Node globals are also absent, so the right environment plus a polyfill is needed.

How to fix it

Polyfill the missing global in setup

Provide the API from Node in a setup file referenced by setupFiles.

jest.setup.js
// jest.setup.js
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

Wire the setup file into Jest

jest.config.js
// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFiles: ['<rootDir>/jest.setup.js'],
};

How to prevent it

  • Keep polyfills in a shared setupFiles module.
  • Pick jsdom for DOM suites and node for pure-logic suites.
  • Pin jest-environment-jsdom, a separate package since Jest 28.

Frequently asked questions

What causes ""TextEncoder is not defined""?
jsdom omits some Web APIs (TextEncoder, crypto.subtle, ResizeObserver, fetch on older setups). Referencing them throws a ReferenceError.
How do I fix "TextEncoder is not defined"?
Provide the API from Node in a setup file referenced by setupFiles.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card