isomorphic-dompurify: Bumping to 0.16.0 - ReferenceError: TextEncoder is not defined

When installing - "isomorphic-dompurify": "^0.16.0" I get the following error within a jest test that previously passed.

Error: ReferenceError: TextEncoder is not defined

js file:

import DOMPurify from "isomorphic-dompurify";

return DOMPurify.sanitize(input.trim(), { ADD_ATTR: ["target"] });

Test:

import sanitize from "./sanitizeHtml";

describe("sanitize", () => {
    it("remove js from input", () => {
        expect(sanitize("<img onload='alert(1)' />")).toEqual("<img>");
    });
});

Any ideas what this may be? Thanks in advance

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 7
  • Comments: 24 (10 by maintainers)

Commits related to this issue

Most upvoted comments

For anyone hitting this same issue, I was able to fix this on a project (which had a failing test due to this error) by including the following in my jest.setup.js file:

import { TextDecoder, TextEncoder } from 'util'

global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder

I’ve tried each one of the solutions provided above but since i’m working with nextJest the tests were failing. I solved it by adding

setupFiles: ["path/to/personalizedJest.setup.js"],

to the personalized configuration for jest, in this file i just imported TextEncoder and TextDecoder from util:

import { TextDecoder, TextEncoder } from 'util';

global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

I’ve tried

import { TextDecoder, TextEncoder } from 'util'

global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder

in my jest setup

but I just get this error:

    TypeError: TextEncoder is not a constructor

    > 5 | import DOMPurify from 'isomorphic-dompurify';

any ideas?

edit:

for anybody having this issue, I fixed it by importing from ‘node:util’ so:

import { TextDecoder, TextEncoder } from 'node:util'

For me, the TextDecoder had a type mismatch issue with the above approach, so I solved it with this syntax instead:

import { TextEncoder, TextDecoder } from 'util';

Object.assign(global, { TextDecoder, TextEncoder });

Thanks to leonheess - https://stackoverflow.com/questions/68468203/why-am-i-getting-textencoder-is-not-defined-in-jest

For me, I had to add the following to jest.setup.js

import { TextDecoder, TextEncoder } from 'util';

global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

and import the lib like import * as dompurify from 'isomorphic-dompurify';