3

I have these two files:

test.js:

const jsdom = require("jsdom");

const hello  = () =>  {
  console.log("hello!");
};


module.exports = {
    hello
};

and

server.js:

const hello = require('./stuff/test');

hello.hello();

directory structure:

myprojectfolder
             backend
                    src
                       stuff
                           test.js
                       server.js

When I run server.js I get the ReferenceError: TextEncoder is not defined error:

/home/myusername/projects/myprojectfolder/node_modules/whatwg-url/lib/encoding.js:2
const utf8Encoder = new TextEncoder();
                    ^

ReferenceError: TextEncoder is not defined

If I remove const jsdom = require("jsdom"); line from test.js, server.js runs fine and without any errors (outputs hello).

Why does it happen and how do I fix it (while still being able to import and use jsdom inside test.js?).

Boaz
  • 19,892
  • 8
  • 62
  • 70
parsecer
  • 4,758
  • 13
  • 71
  • 140
  • 1
    Is this in Node.js and if so which version? – Boaz Feb 17 '22 at 18:57
  • Does this answer your question? [ReferenceError: TextEncoder is not defined](https://stackoverflow.com/questions/19697858/referenceerror-textencoder-is-not-defined) – Boaz Feb 17 '22 at 19:01
  • @Boaz I was using NodeJS version `10`, tried version `16` and it runs fine, thank you! – parsecer Feb 17 '22 at 19:02
  • 2
    Indeed, the `TextEncoder` constructor is only available (globally) from Node 12. This is covered in the duplicate post. – Boaz Feb 17 '22 at 19:03
  • 3
    I'm using nodejs v18 and still get the error. I even installed text-encoder. Still doesn't work. – John Tang Boyland Sep 30 '22 at 00:43

1 Answers1

5

Well, it took me all day, but finally I managed to pull it together. My problem was that tests didn't run because of that error.

So, in package.json under "scripts" I added the following:

"test": "jest --verbose --runInBand --detectOpenHandles --forceExit"

And in jest.config.js, I added the following:

   globals: {
      "ts-jest": {
         tsConfigFile: "tsconfig.json"
       },
       TextEncoder: require("util").TextEncoder,
       TextDecoder: require("util").TextDecoder
   }
Adi Levy
  • 51
  • 1
  • 2