jjnrmason
jjnrmason

Reputation: 311

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.

Upvotes: 4

Views: 1186

Answers (2)

Sortweste
Sortweste

Reputation: 293

You can create a Wrapper Component to work with BrowserRouter

const Wrapper = ({ children }) => {
  return (
    <BrowserRouter>
       {children}
    </BrowserRouter>
  );
};

const renderWithRouter = (ui) => {
  return render(ui, { wrapper: Wrapper});
};

And then you can use it like this:

const { getByTestId } = renderWithRouter(<AccountMenu userDetails={fakeUser} />)

Upvotes: 2

jjnrmason
jjnrmason

Reputation: 311

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.

Upvotes: 5

Related Questions