javascriptjestjsjsdomtextdecoder

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


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?


Solution

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

    import { TextEncoder, TextDecoder } from 'util';
    
    Object.assign(global, { TextDecoder, TextEncoder });
    

    You will have to add that to the test or to a setupFile like setup.jest.ts.