hb0
hb0

Reputation: 3747

ReferenceError: TextEncoder is not defined after react-router-dom upgrade to 7

After upgrading my Create-React-app from "react-router-dom^6.27.0" to react-router^7.1.1:

npm uninstall react-router-dom
npm install react-router@latest

I get the following error when executing my Jest tests npm test:

ReferenceError: TextEncoder is not defined

from
    import { BrowserRouter as Router } from 'react-router' (was react-router-dom before)
and
    import { useNavigate, useParams } from 'react-router' (was react-router-dom before)

When I simply downgrade again, this issue does not occur:

    "react-router": "^6.26.2",
    "react-router-dom": "^6.27.0",

Why does this happen and how to fix this?

I don't find anything about this in the migration notes.

I only find some hacky solutions which seems quite outdated.

Upvotes: 0

Views: 608

Answers (1)

hb0
hb0

Reputation: 3747

As @user19259811 and the linked issue suggests:

You need to add to your Jest Test setup file*:

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

if (!global.TextEncoder) {
  global.TextEncoder = TextEncoder
}

if (!global.TextDecoder) {
  global.TextDecoder = TextDecoder
}

*when you use react-scripts test in your package.json, your Jest Test Setup file is:

./src/setupTests.js

This file is automatically imported by react-scripts test.


Additional notes:

I had issues as my jest.config.js was ignored, until I noticed that I have to configure it in the package.json when using react-scripts test:

  "scripts": {
    ...
    "test": "react-scripts test"
  },
  "jest": { ... configuration ... },

Upvotes: 0

Related Questions