Can't get MemoryRouter to work with @testing-library/react
The problem is, that the component I wanted to test already has a router declared.
To solve this issue I had to split up the App
Component into App
and Routes
.
For the testing I just have to render the Routes
component and everything works as expected.
App.tsx
import React from 'react';
import {Route, Switch, BrowserRouter} from 'react-router-dom';
export const Routes = () => {
return (
<>
<Switch>
<Route path={'/test'}> test</Route>
<Route path={'/'}> index</Route>
</Switch>
</>
)
};
const App: React.FC = () => {
return (
<div>
<BrowserRouter>
<Routes/>
</BrowserRouter>
</div>
);
};
export default App;
App.test.tsx
import React from 'react';
import {Routes} from './App';
import {MemoryRouter} from 'react-router-dom';
import {render} from '@testing-library/react';
test('renders routes correct', async () => {
const app = render(
<MemoryRouter initialEntries={['/test']} initialIndex={0}>
<Routes/>
</MemoryRouter>
);
expect(app.getByText(/test/i)).toBeInTheDocument();
});