Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useCanGoBack.test.tsx

92 lines2.2 KB

1import { beforeEach, describe, expect, test } from 'vitest'
2import { cleanup, fireEvent, render, screen } from '@testing-library/react'
3import {
4 Link,
5 Outlet,
6 RouterProvider,
7 createMemoryHistory,
8 createRootRoute,
9 createRoute,
10 createRouter,
11 useCanGoBack,
12 useLocation,
13 useRouter,
14} from '../src'
15​
16beforeEach(() => {
17 cleanup()
18})
19​
20describe('useCanGoBack', () => {
21 function setup({
22 initialEntries = ['/'],
23 }: {
24 initialEntries?: Array<string>
25 } = {}) {
26 function RootComponent() {
27 const router = useRouter()
28 const location = useLocation()
29 const canGoBack = useCanGoBack()
30​
31 expect(canGoBack).toBe(location.pathname === '/' ? false : true)
32​
33 return (
34 <>
35 <button onClick={() => router.history.back()}>Back</button>
36 <Link to="/">Home</Link>
37 <Link to="/about">About</Link>
38 <Outlet />
39 </>
40 )
41 }
42​
43 const rootRoute = createRootRoute({
44 component: RootComponent,
45 })
46 const indexRoute = createRoute({
47 getParentRoute: () => rootRoute,
48 path: '/',
49 component: () => <h1>IndexTitle</h1>,
50 })
51 const aboutRoute = createRoute({
52 getParentRoute: () => rootRoute,
53 path: '/about',
54 component: () => <h1>AboutTitle</h1>,
55 })
56​
57 const router = createRouter({
58 routeTree: rootRoute.addChildren([indexRoute, aboutRoute]),
59 history: createMemoryHistory({ initialEntries }),
60 })
61​
62 return render(<RouterProvider router={router} />)
63 }
64​
65 test('when no location behind', async () => {
66 setup()
67​
68 const indexTitle = await screen.findByText('IndexTitle')
69 expect(indexTitle).toBeInTheDocument()
70​
71 const aboutLink = await screen.findByText('About')
72 fireEvent.click(aboutLink)
73​
74 const aboutTitle = await screen.findByText('AboutTitle')
75 expect(aboutTitle).toBeInTheDocument()
76 })
77​
78 test('when location behind', async () => {
79 setup({
80 initialEntries: ['/', '/about'],
81 })
82​
83 const aboutTitle = await screen.findByText('AboutTitle')
84 expect(aboutTitle).toBeInTheDocument()
85​
86 const backButton = await screen.findByText('Back')
87 fireEvent.click(backButton)
88​
89 const indexTitle = await screen.findByText('IndexTitle')
90 expect(indexTitle).toBeInTheDocument()
91 })
92})