This post goes over how to fix Jest test errors when upgrading React Router from version 6 to 7:
TextEncoder is not defined
This error occurs when you bump react-router-dom
from version 6 to 7 (see remix-run/react-router#12363):
ReferenceError: TextEncoder is not defined
The fix is to polyfill TextEncoder
in the Node.js environment:
// test/setupFiles.js
import { TextEncoder } from 'util';
global.TextEncoder = TextEncoder;
If your Node.js version does not support this, then install text-encoding
:
npm install --dev text-encoding
// test/setupFiles.js
import { TextEncoder } from 'text-encoding';
global.TextEncoder = TextEncoder;
Update your Jest config with setupFiles:
// jest.config.js
module.exports = {
setupFiles: ['<rootDir>/test/setupFiles.js'],
// ...
};
See example.
Cannot destructure property ‘basename’ of ‘React10.useContext(…)’
If you see this error:
Cannot destructure property 'basename' of 'React10.useContext(...)' as it is null.
Then you should replace:
-import { RouterProvider } from "react-router-dom";
+import { RouterProvider } from "react-router";
This occurs because you need to use a top-level import for non-DOM contexts (e.g., Jest).
See example.