(Jest) useNavigate() may be used only in the context of a Router component

avatar

Borislav Hadzhiev

Tue Apr 19 20222 min read

(Jest) useNavigate() may be used only in the context of a Router component #

The jest error "useNavigate() may be used only in the context of a Router component" occurs when we try to test a component that uses the useNavigate hook without wrapping the component in a Router. To solve the error, wrap the component you're testing in a Router context.

jest usenavigate may only be used in context of router

App.test.js
import {render} from '@testing-library/react'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; // 👇️ must wrap your component in <Router> test('renders react component', async () => { render( <Router> <App />, </Router>, ); });

The error is caused because the component we are testing or one of its children uses the useNavigate hook.

The useNavigate hook can only be used inside of a Router component because it makes use of the context that the Router provides.

If any of the components you are rendering in your test use the useNavigate hook, you have to wrap them in a Router when testing them.

You should also make sure that you have wrapped your application in a Router component.

Here is how you would do that in your index.js file.

index.js
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); // 👇️ wrap App in Router root.render( <Router> <App /> </Router> );

Now you can use the useNavigate hook in your App.js file.

App.js
import React from 'react'; import { useNavigate, } from 'react-router-dom'; export default function App() { const navigate = useNavigate(); const handleClick = () => { // 👇️ navigate programmatically navigate('/about'); }; return ( <div> <button onClick={handleClick}>Navigate to About</button> </div> ); }
The best place to wrap your React app with a Router component is in your index.js file because that's the entry point of your React application.

Once your entire app is wrapped with a Router component, you can use any of the hooks from the react router package anywhere in your components.

Use the search field on my Home Page to filter through my more than 1,000 articles.