How to Fix React Router’s “useNavigate() May Be Used Only in the Context of a Router” Error in Cypress Tests
Fix Cypress’s useNavigate router-context error by wrapping components in MemoryRouter, choosing the right route, and testing route-level code correctly.

If Cypress reports useNavigate() may be used only in the context of a Router, the component calling useNavigate was mounted outside a React Router provider. Add a router above that component in the rendered tree. For most Cypress React component tests, MemoryRouter is the smallest correct fix:
import { MemoryRouter } from 'react-router-dom'
cy.mount(
<MemoryRouter initialEntries={["/login"]}>
<Navigation />
</MemoryRouter>
)
Use initialEntries to start the in-memory history at the path your scenario needs. If the component is a route-level component that depends on loaders, actions, generated route context, or its real route hierarchy, test it through the running application with Cypress end-to-end or integration coverage instead of adding an arbitrary wrapper.
What the error means
useNavigate is a React Router hook. Hooks such as useNavigate, useLocation, and useParams read values from a router context supplied by an ancestor. React Router’s useInRouterContext helper returns whether a component is a descendant of a router, which explains the failure: the hook cannot find that ancestor in Cypress’s mounted tree.
Your production application probably renders a router near its root:
function AppRoot() {
return (
<BrowserRouter>
<App />
</BrowserRouter>
)
}
In a component test, however, Cypress mounts the node you pass to cy.mount. If you mount <Navigation /> directly, the application root is not automatically included. The component is therefore outside any router even though the same component works in the browser.
Cypress’s React component-testing guidance uses MemoryRouter for this situation. React Router describes it as a declarative router that stores its entries in memory, so it does not need to change the browser’s address bar while your test runs. See the Cypress React component-testing examples, the React Router MemoryRouter reference, and the useNavigate reference.
Diagnose the test before changing it
- Locate the hook. Search the component and its children for
useNavigate(). The router must be above the component that calls the hook, not merely beside it. - Identify the Cypress test type. A component test uses
cy.mountand needs test-time providers. An end-to-end test opens the running application and should normally use the application’s existing router setup. - Decide what behavior you are testing. A reusable navigation button may need only a memory router. A route module that relies on route loaders, actions, outlet context, or generated route types usually needs the real route tree.
- Check for an existing wrapper. If your shared mount command already adds a router, adding another one can create conflicting or nested navigation contexts. Keep one deliberate router boundary for the test.
One-off fix with MemoryRouter
For an isolated component, wrap the mounted component directly. Import MemoryRouter from the package that provides your installed router APIs, commonly react-router-dom in a browser React application.

import { MemoryRouter } from 'react-router-dom'
import Navigation from '../../src/Navigation'
describe('Navigation', () => {
it('renders the navigation links', () => {
cy.mount(
<MemoryRouter>
<Navigation />
</MemoryRouter>
)
cy.contains('Home').should('be.visible')
})
})
The default memory history starts at /. That is enough when your component only needs navigation context and does not render different output for another path.
Start at a scenario-specific route
Pass initialEntries when the current location affects active links, conditional UI, redirects, or route parameters:
it('marks Login as the active link', () => {
cy.mount(
<MemoryRouter initialEntries={["/login"]}>
<Navigation />
</MemoryRouter>
)
cy.findByRole('link', { name: 'Login' })
.should('have.attr', 'aria-current', 'page')
})
initialEntries accepts more than strings when you need an entry with a pathname, search string, hash, or state:
<MemoryRouter
initialEntries={[
{ pathname: '/products', search: '?page=2', hash: '#results' },
]}
>
<ProductList />
</MemoryRouter>
When there are several entries, initialIndex chooses the active position in the in-memory history stack:
<MemoryRouter
initialEntries={['/start', '/checkout', '/complete']}
initialIndex={1}
>
<Checkout />
</MemoryRouter>
This lets you test back and forward behavior without changing the real browser URL.
Create a reusable Cypress mount command
If many components use router hooks, put the provider in your custom mount command. This keeps individual tests focused on behavior and gives every test a predictable default route.
// cypress/support/component.tsx
import { mount } from 'cypress/react'
import { MemoryRouter, type MemoryRouterProps } from 'react-router-dom'
Cypress.Commands.add('mount', (component, options = {}) => {
const {
routerProps = { initialEntries: ['/'] },
...mountOptions
} = options
const wrapped = (
<MemoryRouter {...routerProps}>
{component}
</MemoryRouter>
)
return mount(wrapped, mountOptions)
})
Keep your project’s existing mount options, providers, and command declarations when adapting this pattern. In TypeScript, extend the Cypress Chainable interface so routerProps is part of the custom command’s options:
declare global {
namespace Cypress {
interface Chainable {
mount(
component: React.ReactNode,
options?: {
routerProps?: MemoryRouterProps
[key: string]: unknown
}
): Chainable<void>
}
}
}
export {}
Use the default route for components that do not care about location:
cy.mount(<ProfileMenu />)
Override it for a particular scenario:
cy.mount(<Navigation />, {
routerProps: { initialEntries: ['/login'] },
})
If your project has a typed application-specific options object, merge routerProps into that type rather than replacing it. The important property is that the final rendered component is a descendant of exactly the router you intended.
When MemoryRouter is not the right test boundary
Testing a route-level component
A route-level component can depend on more than navigation. It may expect a loader’s data, an action, an outlet, route handles, generated route types, or framework-mode context. Wrapping it in MemoryRouter can remove the immediate exception while leaving the test unlike the application.
React Router documents createRoutesStub for certain reusable components that need contextual route data. The same guidance recommends integration or end-to-end tests against a running application for route components. Use the narrowest test boundary that represents the behavior:
- Reusable component: use
MemoryRouter, adding route stubs only for the context the component actually consumes. - Route module: exercise the configured route tree, loaders, and actions through an integration or end-to-end test.
- Navigation between real pages: start the application and let its production router handle the transition.
Testing the running app with Cypress E2E
An end-to-end test normally visits the application rather than mounting a child:
describe('login navigation', () => {
it('opens the login page', () => {
cy.visit('/')
cy.findByRole('link', { name: 'Login' }).click()
cy.location('pathname').should('eq', '/login')
})
})
Do not add a second browser router around a page that already has one. The application entry point should own that provider.
Common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
| The same useNavigate error remains | The router wraps a sibling or a different element than the component under test. | Inspect the JSX passed to cy.mount and place the component inside MemoryRouter. |
| The test renders but active-link assertions fail | The memory history starts at /, while the assertion expects another path. |
Set initialEntries to the scenario path, such as ['/login']. |
| A nested router warning appears | A shared custom mount and the test both add routers. | Remove the one-off wrapper or disable the shared wrapper for that test; keep one intentional router. |
| Route data or outlet context is undefined | The component is a route module requiring more than navigation context. | Use the real route tree in integration/E2E coverage, or a carefully configured route stub for a reusable component. |
| Imports fail after upgrading React Router | Package entry points and router modes differ by installed version. | Follow the API imports documented for your installed release. The Cypress example commonly imports MemoryRouter from react-router-dom; newer references may show hooks from react-router. |
| The test suppresses the exception and passes | Exception handling hides a real missing-provider defect. | Only suppress an exception when the test deliberately asserts render-error behavior. Supply the required context for normal tests. |
| Navigation assertions are flaky | The test checks too early or asserts a browser URL for a memory-only router. | Assert rendered state after the action, or inspect the component’s visible result. A MemoryRouter does not need to update the address bar. |

Router versions and navigate behavior
Match the wrapper and imports to the React Router release installed in your project. React Router documents different behavior for useNavigate in Declarative, Data, and Framework modes; its return type can be void or Promise<void> depending on mode. That typing nuance does not change the provider requirement: the calling component still has to be rendered under a router.
If a component conditionally calls navigation after an event, test the user-visible result rather than implementation details. For example, click a button and assert that a success panel appears, a callback fires, or a link becomes active. Keep route setup explicit so a future maintainer can see why the starting location matters.
Performance, reliability, and maintenance
- Keep the wrapper small. A memory router avoids launching a server or changing the browser URL, so it is suitable for fast component tests.
- Use stable initial entries. Set one meaningful path per scenario instead of relying on whichever route a shared helper happened to use.
- Separate test levels. Component tests should verify reusable behavior with the providers it needs. Route wiring, loaders, redirects, and authentication boundaries belong in higher-level tests.
- Do not overconfigure history. Add multiple entries and an
initialIndexonly when back/forward history is part of the behavior under test. - Keep provider ownership clear. Document whether the custom mount supplies the router. This prevents duplicate wrappers when new tests are added.
- Use accessible assertions. Prefer role and name queries for navigation controls, then assert the resulting UI or location state.
Or skip the browser setup
If your broader workflow needs screenshots of the pages involved in a Cypress investigation, ScreenshotNeo provides a website screenshot API and MCP server. It accepts one GET request and returns PNG, JPEG, WebP, or PDF output. Its cleanup steps can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off.
See the ScreenshotNeo API documentation for the complete option list. The basic calls are:
cURL
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://screenshotneo.com \
-o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://screenshotneo.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://screenshotneo.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response reports the result with X-Page-Verdict and X-Billed headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
For test fixtures and visual documentation, you can also choose full-page capture with lazy images loaded, a CSS-selector element capture, dark mode, device presets or a custom viewport, retina scale, custom CSS and JavaScript, click actions, selector waits, delays, network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, configurable TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, and a usage API. The plans include 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
FAQ
Can I use BrowserRouter in a Cypress component test?
You can, but MemoryRouter is usually clearer because it keeps history in memory and does not depend on browser URL behavior. Use the router that matches the behavior you need to verify.
Does initialEntries navigate the real browser?
No. It initializes the memory history used by the mounted tree. The browser address bar is not the source of truth for that component test.
Why does adding a router reveal a different error?
The original missing-context error was fixed, allowing execution to reach another missing dependency, such as loader data, an outlet, or authentication context. Add the specific provider only if the component is reusable; otherwise move the test to the route-level boundary.
Should I mock useNavigate?
Usually no. Supplying a real memory router verifies that the component interacts with React Router correctly and keeps the test closer to user behavior. Mock the hook only when you are intentionally testing an isolated unit boundary.
Which path should initialEntries use?
Use the path represented by the scenario: /login for a login-page state, /account/settings for a settings link, or an entry object when search, hash, or state affects rendering.


