|
| 1 | +// @vitest-environment jsdom |
| 2 | +import { createResource, Suspense } from "solid-js"; |
| 3 | +import { render } from "solid-js/web"; |
| 4 | +import { MemoryRouter, Route, createMemoryHistory, useNavigate } from "../src/index.jsx"; |
| 5 | +import type { Navigator } from "../src/types.js"; |
| 6 | + |
| 7 | +const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); |
| 8 | + |
| 9 | +describe("pending navigation", () => { |
| 10 | + test("navigating back to the shown route cancels a pending navigation", async () => { |
| 11 | + let resolveSlow!: (value: string) => void; |
| 12 | + const Slow = () => { |
| 13 | + const [value] = createResource(() => new Promise<string>(resolve => (resolveSlow = resolve))); |
| 14 | + return <span>Slow {value()}</span>; |
| 15 | + }; |
| 16 | + let navigate!: Navigator; |
| 17 | + const history = createMemoryHistory(); |
| 18 | + history.set({ value: "/a", scroll: false }); |
| 19 | + const root = document.createElement("div"); |
| 20 | + const dispose = render( |
| 21 | + () => ( |
| 22 | + <MemoryRouter |
| 23 | + history={history} |
| 24 | + root={props => { |
| 25 | + navigate = useNavigate(); |
| 26 | + return ( |
| 27 | + <> |
| 28 | + <p id="location">{props.location.pathname}</p> |
| 29 | + <Suspense fallback={<span>Loading</span>}>{props.children}</Suspense> |
| 30 | + </> |
| 31 | + ); |
| 32 | + }} |
| 33 | + > |
| 34 | + <Route path="/" component={() => <span>Home</span>} /> |
| 35 | + <Route path="/a" component={() => <span>Page A</span>} /> |
| 36 | + <Route path="/slow" component={Slow} /> |
| 37 | + </MemoryRouter> |
| 38 | + ), |
| 39 | + root |
| 40 | + ); |
| 41 | + |
| 42 | + try { |
| 43 | + await wait(10); |
| 44 | + expect(root.textContent).toContain("Page A"); |
| 45 | + navigate("/slow"); |
| 46 | + await wait(10); |
| 47 | + expect(root.textContent).toContain("Page A"); |
| 48 | + navigate("/a"); |
| 49 | + await wait(10); |
| 50 | + resolveSlow("loaded"); |
| 51 | + await wait(25); |
| 52 | + expect(history.get()).toBe("/a"); |
| 53 | + expect(root.querySelector("#location")?.textContent).toBe("/a"); |
| 54 | + expect(root.textContent).toContain("Page A"); |
| 55 | + expect(root.textContent).not.toContain("Slow"); |
| 56 | + |
| 57 | + // no duplicate /a entry was pushed |
| 58 | + history.back(); |
| 59 | + await wait(10); |
| 60 | + expect(history.get()).toBe("/"); |
| 61 | + } finally { |
| 62 | + dispose(); |
| 63 | + } |
| 64 | + }); |
| 65 | +}); |
0 commit comments