4

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

don't forgot to import import { BrowserRouter } from "react-router-dom"
2

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} />)

1 Comment

Ahh okay that's cool. Little cleaner too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.