|
1 | 1 | import * as React from "react"; |
2 | 2 | import * as TestRenderer from "react-test-renderer"; |
3 | | -import { MemoryRouter, Outlet, Routes, Route, useParams } from "react-router"; |
| 3 | +import { |
| 4 | + MemoryRouter, |
| 5 | + Outlet, |
| 6 | + Routes, |
| 7 | + Route, |
| 8 | + useParams, |
| 9 | + useLocation, |
| 10 | + generatePath, |
| 11 | +} from "react-router"; |
4 | 12 |
|
5 | 13 | function ShowParams() { |
6 | 14 | return <pre>{JSON.stringify(useParams())}</pre>; |
@@ -209,4 +217,72 @@ describe("useParams", () => { |
209 | 217 | `); |
210 | 218 | }); |
211 | 219 | }); |
| 220 | + |
| 221 | + test("maintains compatibility with generatePath", () => { |
| 222 | + let tests = [ |
| 223 | + { |
| 224 | + path: "/books/42", |
| 225 | + url: "/books/42", |
| 226 | + params: {}, |
| 227 | + }, |
| 228 | + { |
| 229 | + path: "/books/:id", |
| 230 | + url: "/books/42", |
| 231 | + params: { id: "42" }, |
| 232 | + }, |
| 233 | + { |
| 234 | + path: "/books/:id.json", |
| 235 | + url: "/books/42.json", |
| 236 | + params: { id: "42" }, |
| 237 | + }, |
| 238 | + { |
| 239 | + path: "/books/:id/comments", |
| 240 | + url: "/books/42/comments", |
| 241 | + params: { id: "42" }, |
| 242 | + }, |
| 243 | + { |
| 244 | + path: "/books/:id.json/comments", |
| 245 | + url: "/books/42.json/comments", |
| 246 | + params: { id: "42" }, |
| 247 | + }, |
| 248 | + ]; |
| 249 | + |
| 250 | + function ShowParamsAndPath({ path }: { path: string }) { |
| 251 | + return ( |
| 252 | + <> |
| 253 | + <p>{JSON.stringify(useParams())}</p> |
| 254 | + <p>{useLocation().pathname}</p> |
| 255 | + <p>{generatePath(path, useParams())}</p> |
| 256 | + </> |
| 257 | + ); |
| 258 | + } |
| 259 | + |
| 260 | + for (let { path, url, params } of tests) { |
| 261 | + let renderer: TestRenderer.ReactTestRenderer; |
| 262 | + TestRenderer.act(() => { |
| 263 | + renderer = TestRenderer.create( |
| 264 | + <MemoryRouter initialEntries={[url]}> |
| 265 | + <Routes> |
| 266 | + <Route path={path} element={<ShowParamsAndPath path={path} />} /> |
| 267 | + </Routes> |
| 268 | + </MemoryRouter>, |
| 269 | + ); |
| 270 | + }); |
| 271 | + |
| 272 | + // eslint-disable-next-line jest/no-interpolation-in-snapshots |
| 273 | + expect(renderer.toJSON()).toMatchInlineSnapshot(` |
| 274 | + [ |
| 275 | + <p> |
| 276 | + ${JSON.stringify(params)} |
| 277 | + </p>, |
| 278 | + <p> |
| 279 | + ${url} |
| 280 | + </p>, |
| 281 | + <p> |
| 282 | + ${url} |
| 283 | + </p>, |
| 284 | + ] |
| 285 | + `); |
| 286 | + } |
| 287 | + }); |
212 | 288 | }); |
0 commit comments