admin管理员组

文章数量:1122832

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.

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.

Share Improve this question edited yesterday hb0 asked yesterday hb0hb0 3,7176 gold badges33 silver badges58 bronze badges 2
  • 2 I found an open issue for this here: github.com/remix-run/react-router/issues/12363 – hb0 Commented yesterday
  • 2 in the jest setup js, try adding import { TextDecoder, TextEncoder } from 'util'; global.TextEncoder = TextEncoder; global.TextDecoder = TextDecoder; – user19259811 Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 0

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 ... },

本文标签: ReferenceError TextEncoder is not defined after reactrouterdom upgrade to 7Stack Overflow