|
| 1 | +import React from "react"; |
| 2 | +import ReactDOM from "react-dom"; |
| 3 | +import { MemoryRouter, Route, useMatch, useParams } from "react-router"; |
| 4 | + |
| 5 | +import renderStrict from "./utils/renderStrict.js"; |
| 6 | + |
| 7 | +describe("useParams", () => { |
| 8 | + const node = document.createElement("div"); |
| 9 | + |
| 10 | + afterEach(() => { |
| 11 | + ReactDOM.unmountComponentAtNode(node); |
| 12 | + }); |
| 13 | + |
| 14 | + describe("when the path has no params", () => { |
| 15 | + it("returns an empty hash", () => { |
| 16 | + let params; |
| 17 | + |
| 18 | + function HomePage() { |
| 19 | + params = useParams(); |
| 20 | + return null; |
| 21 | + } |
| 22 | + |
| 23 | + renderStrict( |
| 24 | + <MemoryRouter initialEntries={["/home"]}> |
| 25 | + <Route path="/home"> |
| 26 | + <HomePage /> |
| 27 | + </Route> |
| 28 | + </MemoryRouter>, |
| 29 | + node |
| 30 | + ); |
| 31 | + |
| 32 | + expect(typeof params).toBe("object"); |
| 33 | + expect(Object.keys(params)).toHaveLength(0); |
| 34 | + }); |
| 35 | + }); |
| 36 | + |
| 37 | + describe("when the path has some params", () => { |
| 38 | + it("returns a hash of the URL params and their values", () => { |
| 39 | + let params; |
| 40 | + |
| 41 | + function BlogPost() { |
| 42 | + params = useParams(); |
| 43 | + return null; |
| 44 | + } |
| 45 | + |
| 46 | + renderStrict( |
| 47 | + <MemoryRouter initialEntries={["/blog/cupcakes"]}> |
| 48 | + <Route path="/blog/:slug"> |
| 49 | + <BlogPost /> |
| 50 | + </Route> |
| 51 | + </MemoryRouter>, |
| 52 | + node |
| 53 | + ); |
| 54 | + |
| 55 | + expect(typeof params).toBe("object"); |
| 56 | + expect(params).toMatchObject({ |
| 57 | + slug: "cupcakes" |
| 58 | + }); |
| 59 | + }); |
| 60 | + |
| 61 | + describe("a child route", () => { |
| 62 | + it("returns a combined hash of the parent and child params", () => { |
| 63 | + let params; |
| 64 | + |
| 65 | + function Course() { |
| 66 | + params = useParams(); |
| 67 | + return null; |
| 68 | + } |
| 69 | + |
| 70 | + function Users() { |
| 71 | + const match = useMatch(); |
| 72 | + return ( |
| 73 | + <div> |
| 74 | + <h1>Users</h1> |
| 75 | + <Route path={`${match.path}/courses/:course`}> |
| 76 | + <Course /> |
| 77 | + </Route> |
| 78 | + </div> |
| 79 | + ); |
| 80 | + } |
| 81 | + |
| 82 | + renderStrict( |
| 83 | + <MemoryRouter |
| 84 | + initialEntries={["/users/mjackson/courses/react-router"]} |
| 85 | + > |
| 86 | + <Route path="/users/:username"> |
| 87 | + <Users /> |
| 88 | + </Route> |
| 89 | + </MemoryRouter>, |
| 90 | + node |
| 91 | + ); |
| 92 | + |
| 93 | + expect(typeof params).toBe("object"); |
| 94 | + expect(params).toMatchObject({ |
| 95 | + username: "mjackson", |
| 96 | + course: "react-router" |
| 97 | + }); |
| 98 | + }); |
| 99 | + }); |
| 100 | + }); |
| 101 | +}); |
0 commit comments