1

I am trying to run jest test cases but I am facing error -

ReferenceError: TextEncoder is not defined .

Node version -14.18.0.

Mongodb NPM - 4.1.3 .

Typescript version - 4.4.3.

Below is my test code --

beforeAll(() => {
  connection = new Connection();
});

Below is my connection class code

import { MongoClient, Db, MongoClientOptions } from 'mongodb';

class MongoConnection {
  
public async conn(){
    await MongoClient.connect('', options);
}
}

Error --

FAIL connection.test.ts

● Test suite failed to run

ReferenceError: TextEncoder is not defined

  
> 1 | import { MongoClient, Db, MongoClientOptions } from 'mongodb';
Soham
  • 4,397
  • 11
  • 43
  • 71

2 Answers2

4

Ok the problem got solved.

I have added at the top --

global.TextEncoder = require("util").TextEncoder;
global.TextDecoder = require("util").TextDecoder;

Not sure why the error was showing.

Soham
  • 4,397
  • 11
  • 43
  • 71
0

For a more complete answer:

When the newer packages of mongodb get installed (at leats with v4.11.0) it has the mongodb-connection-string-url package as a dependency and that in turn, has the whatwg-url package as a dependeny.

It seems the whatwg-url package is missing a line at the top of the encoding.js file in node_modules/whatwg-url/lib/encoding.js.

The line to be added is:

const { TextEncoder, TextDecoder } = require('util'); //this line needs to be added
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });

...

This solves the problem, but if the node modules are deleted and installed again, the same problem will reappear, which is not ideal. Would like to know if there is a better alternative then to manually adjust this file...

Oliver Wagner
  • 170
  • 2
  • 10