reactjsreact-routerreact-testing-libraryreact-typescriptreact-test-renderer

Error when running unit test "You should not use <Link> outside a <Router>"


I have a unit test here and I am performing a click event. I am getting the error:
Invariant failed: You should not use <Link> outside a <Router>

describe("when the menu icon has been clicked", () => {
    test("the account menu should be displayed", () => {
        const { getByTestId } = render(<AccountMenu userDetails={fakeUser}></AccountMenu>);
        const button = getByTestId("button-icon-element");
        fireEvent.click(button);
        screen.debug();
    });
});

I am pretty sure I know why it's crying but wondering if there is a simple way to get around this whilst unit testing. The unit testing frame work I'm using is @testing-libary/react.


Solution

  • You are required to wrap any elements being tested in a BrowserRouter.

    const { getByTestId } = render(<BrowserRouter><AccountMenu userDetails={fakeUser}></AccountMenu></BrowserRouter>);
    

    And then it can be clicked.