Temporary repository to reproduce issue with react-router when run in vitest, the root depends on react-router, and another dependency also has a peer dependency on react-router.
In that case, when that dependency imports from react-router, it ends with a different instance than the one resolved for the root project imports.
The project includes two components in the src dir, App and DummyComponent.
Apponly creates aBrowserRouterand addsDummyComponentinside of it.DummyComponentimports a hook from the@shlinkio/shlink-frontend-kitpackage, which internally importsuseLocationfromreact-router.
When this is bundled for the web with vite, everything works as expected, but when trying to render DummyComponent in a vitest test, it errors with useLocation() may be used only in the context of a <Router> component, even if the test makes sure to wrap it in a MemoryRouter (or any other kind of router).
The issue is reproducible with node 22.12 or later. It works as expected with older node.js versions.
- Clone this:
git clone git@github.com:acelaya/peer-react-router-vitest.git. - Make sure you are using node
22.12or newer. Instructions can be found here https://nodejs.org/en/download - Install dependencies:
npm install. - Open in the browser:
npm run dev. You should be able to open the URL in printed in the console, and see no errors. - Run tests with vitest:
npm run test. The only existing test should fail withError: useLocation() may be used only in the context of a <Router> component.