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.
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
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;Wire the setup file into Jest
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFiles: ['<rootDir>/jest.setup.js'],
};How to prevent it
- Keep polyfills in a shared
setupFilesmodule. - Pick
jsdomfor DOM suites andnodefor pure-logic suites. - Pin
jest-environment-jsdom, a separate package since Jest 28.