Search code examples
reactjsunit-testingreact-router-domreact-testing-library

Error: useHref() may be used only in the context of a <Router> component when testing


I have a React project that I am trying to add tests to with React Testing Library. I keep getting this error when I run my tests: Error: useHref() may be used only in the context of a <Router> component. I did find a couple questions on here with that error and I tried the solutions with no success. I know it has something to do with React Router Dom. Maybe someone can spot what I am doing wrong.

Here is my App.js:

import React, { useState } from 'react';
import Providers from './context/GlobalContextProviders';
import {
    BrowserRouter as Router,
    Route,
    Routes
} from 'react-router-dom';

import './styles/App.scss';
import { Header } from './components/containers';
import Main from './components/views/Main';
import UsersCenter from './components/views/UsersCenter';
import IngredientsCenter from './components/views/IngredientsCenter';
import NavMenu from './components/containers/NavMenu';
import CSFCenter from './components/views/CSFCenter';

const App = () => {
    const [showUserSettings, setShowUserSettings] = useState(false);
    const [showNavMenu, setShowNavMenu] = useState(false);

    return (
        <Providers>
            <div className={'App'}>
                <Router>
                    <div className={'container-fluid g-0'}>
                        <Header
                            title={'Quotes System IngredientsCenter'}
                            showUserSettings={showUserSettings}
                            setShowUserSettings={setShowUserSettings}
                            showNavMenu={showNavMenu}
                            setShowNavMenu={setShowNavMenu}
                        />
                        {showNavMenu && (
                            <NavMenu setShowNavMenu={setShowNavMenu} />
                        )}
                        <Routes>
                            <Route path={'/'} element={<Main />} />
                            <Route path={'/users'} element={<UsersCenter />} />
                            <Route
                                path={'/ingredients'}
                                element={<IngredientsCenter />}
                            />
                            <Route path={'/CSFCenter'} element={<CSFCenter />} />
                        </Routes>
                    </div>
                </Router>
            </div>
        </Providers>
    );
};

export default App;

And then my test:

import {
    render,
    screen,
    within,
    fireEvent,
    waitFor
} from '@testing-library/react';
import ReactModal from 'react-modal';
import IngredientsCenter from '../views/IngredientsCenter';

test('The ingredients table exists on the screen', async () => {
    render(
        // ReactModal.setAppElement(document.createElement('div')),
        <IngredientsCenter />
    );
    const ingredientsTable = screen.getByRole('ingredients-table');
    await waitFor(() => {
        expect(ingredientsTable).toBeTruthy();
    });
});

Solution

  • When a component requires context of some sort (e.g. with Redux's connect()ed components, or here with react-router), instead of just rendering the component itself,

    render(<IngredientsCenter />);
    

    you'll need to wrap it in the provider(s) it requires:

    render(<Router><IngredientsCenter /></Router>);
    

    If you find yourself needing to do that a lot, you can of course write a wrapper:

    function renderWithProviders(el) {
      render(<Providers><Router>{el}</Router></Providers>);
    }