Skip to content

Commit 17047f1

Browse files
authored
Docs: Add section for testing routes with react router v6 (#1737)
1 parent f2e7ff0 commit 17047f1

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

docusaurus/docs/shared/_migrate-to-react-router-v6.mdx

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Follow the steps below to start using `react-router` v6 in your plugin:
1616

1717
Enable using `react-router@v6` by setting the following feature flag in `<project-root>/.cprc.json`:
1818

19-
```json
19+
```json title="<project-root>/.cprc.json"
2020
{
2121
"features": {
2222
"useReactRouterV6": true
@@ -32,7 +32,7 @@ After updating the build configuration, it is likely that you will need to make
3232

3333
#### 2. Use `<Routes>` instead of `<Switch>`
3434

35-
```typescript
35+
```typescript title="src/Routes.tsx"
3636
// Using <Routes> instead of <Switch> in `react-router` v6
3737
import { Routes } from 'react-router-dom';
3838

@@ -47,7 +47,7 @@ return (
4747

4848
#### 3. Remove the `exact` prop from `<Route>` components
4949

50-
```typescript
50+
```typescript title="src/Routes.tsx"
5151
return (
5252
<Routes>
5353
{/* BAD (Until v5) */}
@@ -60,6 +60,34 @@ return (
6060
);
6161
```
6262

63-
#### 4. Follow the original `react-router` migration guide for more in-depth changes
63+
#### 4. Fix test failures with location service methods
64+
65+
When using `locationService.replace()`, `locationService.push()`, or similar methods from `@grafana/runtime`, your tests might fail after migrating to React Router v6. Solve this by using the `<LocationServiceProvider />` component (introduced in Grafana 11.2.0) to create a provider for the location service in your tests.
66+
67+
```typescript title="test/test-utils.tsx"
68+
import { locationService, LocationServiceProvider } from '@grafana/runtime';
69+
import React, { useEffect, useState } from 'react';
70+
import { Router } from 'react-router-dom';
71+
72+
const history = locationService.getHistory();
73+
74+
export function TestRoutesProvider({ children }: { children: React.ReactNode }) {
75+
const [location, setLocation] = useState(history.location);
76+
77+
useEffect(() => {
78+
history.listen(setLocation);
79+
}, []);
80+
81+
return (
82+
<LocationServiceProvider service={locationService}>
83+
<Router navigator={history} location={location}>
84+
{children}
85+
</Router>
86+
</LocationServiceProvider>
87+
);
88+
}
89+
```
90+
91+
#### 5. Follow the original `react-router` migration guide for more in-depth changes
6492

6593
Visit the [official react-router v5 to v6 migration guide](https://reactrouter.com/en/main/upgrading/v5) for more information.

0 commit comments

Comments
 (0)