1

I have a component which contains a Link component from react router dom v6.

MyComponent.jsx

...

<Link to='/path'>
   Som Text
</Link>

...

But if I try to render this component using react testing library.

render(
    <BrowserRouter>
        <MyComponent />
    </BrowserRouter>,
);

I get this error - TypeError: Cannot read properties of undefined (reading 'createHref').

I have tried removing Link from the component and just replacing it with div. The error goes away so it means it is coming from the Link component.

0

1 Answer 1

0

Many unit test environments tend to be non-DOM environments, so using the BrowserRouter might not be the best choice of router to use. The MemoryRouter is ideally suited for non-DOM environments.

A <MemoryRouter> stores its locations internally in an array. Unlike <BrowserHistory> and <HashHistory>, it isn't tied to an external source, like the history stack in a browser. This makes it ideal for scenarios where you need complete control over the history stack, like testing.

In your unit tests for components that require a routing context be provided to them, e.g. components that render Links and Routes, you should import and wrap these components with the MemoryRouter.

import { MemoryRouter } from 'react-router-dom';

...

<MemoryRouter>
  <MyComponent />
</MemoryRouter>
Sign up to request clarification or add additional context in comments.

Comments

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.