-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
Closed
Labels
Description
Reproduction
https://github.com/azangru/problem-react-router-with-vitest/tree/main
System Info
System:
OS: macOS 15.7.1
CPU: (12) arm64 Apple M4 Pro
Memory: 730.78 MB / 24.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 22.15.0 - ~/.nvm/versions/node/v22.15.0/bin/node
npm: 11.6.1 - ~/.nvm/versions/node/v22.15.0/bin/npm
Browsers:
Chrome: 140.0.7339.208
Safari: 26.0.1
npmPackages:
react-router: 7.9.3 => 7.9.3Used Package Manager
npm
Expected Behavior
In a test environment, MemoryRouter should provide the appropriate context for useLocation.
Actual Behavior
In my minimal reproduction, the test component (TestComponent) attempts to access the location object from React Router through the useLocation hook:
import { useLocation } from 'react-router-dom';
const TestComponent = () => {
const location = useLocation();
return <div>Hello from test</div>
}
TestComponent is wrapped in MemoryRouter for rendering:
import { render } from '@testing-library/react';
const renderComponent = (
params: { url: string } = {
url: '/'
}
) => {
return render(
<MemoryRouter initialEntries={[params.url]}>
<TestComponent />
</MemoryRouter>
);
};
Yet, during rendering, an error occurs, with a message about a missing react router context as if MemoryRouter were not there:
FAIL src/index.test.tsx > My problem > renders without error
Error: useLocation() may be used only in the context of a <Router> component.
❯ invariant node_modules/react-router/dist/development/chunk-NISHYRIK.mjs:188:11
❯ useLocation node_modules/react-router/dist/development/chunk-NISHYRIK.mjs:4988:3
❯ TestComponent src/index.test.tsx:19:20
17|
18| const TestComponent = () => {
19| const location = useLocation();
| ^
20|
21| return <div>Hello from test</div>
❯ Object.react_stack_bottom_frame node_modules/react-dom/cjs/react-dom-client.development.js:25904:20
❯ renderWithHooks node_modules/react-dom/cjs/react-dom-client.development.js:7662:22
❯ updateFunctionComponent node_modules/react-dom/cjs/react-dom-client.development.js:10166:19
❯ beginWork node_modules/react-dom/cjs/react-dom-client.development.js:11778:18
❯ runWithFiberInDEV node_modules/react-dom/cjs/react-dom-client.development.js:874:13
❯ performUnitOfWork node_modules/react-dom/cjs/react-dom-client.development.js:17641:22
❯ workLoopSync node_modules/react-dom/cjs/react-dom-client.development.js:17469:41
Is there anything I am missing?