JEST ReferenceError: TextDecoder is not defined

  Kiến thức lập trình

I am trying to upgrade from my MongoDB NodeJS driver version ^3.5.5 to v4.7.0 and in doing so, I am getting the following error:

    ReferenceError: TextDecoder is not defined

  1 | import { adaptInsertOne } from '../mongoDb/adaptInsertOne'
> 2 | import { ObjectId } from 'mongodb'

My mongodb cluster version is v6.0.15. I am using node v18.12.1. Likewise, my app is created using Create-React-App so its whatever version of JEST was included.

I did some research and unfortunately i cant override the JEST testEnvironment option without ejecting from CRA which isnt an option at the moment, however, the only workaround i found is to add the following lines to the actual UUT (not even the test file itself):

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

But this isnt a good solution at the moment since i’d have to add these lines everywhere i am importing ObjectId.

I’m still unsure as to what exactly is breaking here as a result of upgrading the mongodb nodejs driver version, however, is there a better global solution I can implement without having to do the import code above everywhere i am using ObjectId?