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

searchMiddleware.test.tsx

190 lines5.3 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { cleanup, fireEvent, render, screen } from '@testing-library/react'
3​
4import {
5 Link,
6 RouterProvider,
7 createBrowserHistory,
8 createRootRoute,
9 createRoute,
10 createRouter,
11 retainSearchParams,
12 stripSearchParams,
13} from '../src'
14import { getSearchParamsFromURI } from './utils'
15import type { AnyRouter, RouterHistory } from '../src'
16import type { SearchMiddleware } from '@tanstack/router-core'
17​
18let history: RouterHistory
19​
20beforeEach(() => {
21 history = createBrowserHistory()
22 expect(window.location.pathname).toBe('/')
23})
24​
25afterEach(() => {
26 history.destroy()
27 window.history.replaceState(null, 'root', '/')
28 vi.clearAllMocks()
29 vi.resetAllMocks()
30 cleanup()
31})
32​
33function setupTest(opts: {
34 initial: { route: string; search?: { value?: string } }
35 middlewares: Array<SearchMiddleware<any>>
36 linkSearch?: { value?: string }
37}) {
38 const rootRoute = createRootRoute({
39 validateSearch: (input) => {
40 if (input.value !== undefined) {
41 return { value: input.value as string }
42 }
43 return {}
44 },
45 search: {
46 middlewares: opts.middlewares,
47 },
48 })
49 const indexRoute = createRoute({
50 getParentRoute: () => rootRoute,
51 path: '/',
52 component: () => {
53 return (
54 <>
55 <h1>Index</h1>
56 {/* N.B. this link does not have search params set, but the middleware will add `root` if it is currently present */}
57 <Link data-testid="posts-link" to="/posts" search={opts.linkSearch}>
58 Posts
59 </Link>
60 </>
61 )
62 },
63 })
64​
65 const PostsComponent = () => {
66 const { value } = postsRoute.useSearch()
67 return (
68 <>
69 <h1 data-testid="posts-heading">Posts</h1>
70 <div data-testid="search">{value ?? '$undefined'}</div>
71 </>
72 )
73 }
74​
75 const postsRoute = createRoute({
76 getParentRoute: () => rootRoute,
77 path: 'posts',
78 component: PostsComponent,
79 })
80​
81 const router = createRouter({
82 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
83 history,
84 })
85 window.history.replaceState(
86 null,
87 '',
88 `${opts.initial.route}?${new URLSearchParams(opts.initial.search).toString()}`,
89 )
90 return router
92​
93async function runTest(
94 router: AnyRouter,
95 expectedSearch: { root: { value?: string }; posts: { value?: string } },
96) {
97 render(<RouterProvider router={router} />)
98​
99 const postsLink = await screen.findByTestId('posts-link')
100 expect(postsLink).toHaveAttribute('href')
101 const href = postsLink.getAttribute('href')
102 const linkSearchOnRoot = getSearchParamsFromURI(href!)
103 checkLocationSearch(expectedSearch.root)
104 expect(router.state.location.search).toEqual(expectedSearch.root)
105​
106 fireEvent.click(postsLink)
107​
108 const postHeading = await screen.findByTestId('posts-heading')
109 expect(postHeading).toBeInTheDocument()
110 expect(window.location.pathname).toBe('/posts')
111​
112 expect(await screen.findByTestId('search')).toHaveTextContent(
113 expectedSearch.posts.value ?? '$undefined',
114 )
115 checkLocationSearch(expectedSearch.posts)
116 expect(router.state.location.search).toEqual(expectedSearch.posts)
117 return linkSearchOnRoot
119​
120function checkLocationSearch(search: object) {
121 const parsedSearch = new URLSearchParams(window.location.search)
122 expect(parsedSearch.size).toBe(Object.keys(search).length)
123 for (const [key, value] of Object.entries(search)) {
124 expect(parsedSearch.get(key)).toBe(value)
125 }
127​
128describe('retainSearchParams', () => {
129 const middlewares = [retainSearchParams(['value'])]
130​
131 it('should retain `value` search param', async () => {
132 const router = setupTest({
133 initial: { route: '/', search: { value: 'abc' } },
134 middlewares,
135 })
136 const linkSearch = await runTest(router, {
137 root: { value: 'abc' },
138 posts: { value: 'abc' },
139 })
140 expect(linkSearch.size).toBe(1)
141 expect(linkSearch.get('value')).toBe('abc')
142 })
143​
144 it('should do nothing if `value` search param is not set', async () => {
145 const router = setupTest({ initial: { route: '/' }, middlewares })
146 const expectedLocationSearch = {}
147 const linkSearch = await runTest(router, { root: {}, posts: {} })
148 expect(linkSearch.size).toBe(0)
149 expect(router.state.location.search).toEqual(expectedLocationSearch)
150 checkLocationSearch(expectedLocationSearch)
151 })
152})
153​
154describe('stripSearchParams', () => {
155 it('by key', async () => {
156 const middlewares = [stripSearchParams(['value'])]
157 const router = setupTest({
158 initial: { route: '/', search: { value: 'abc' } },
159 middlewares,
160 linkSearch: { value: 'xyz' },
161 })
162 const linkSearch = await runTest(router, { root: {}, posts: {} })
163 expect(linkSearch.size).toBe(0)
164 })
165​
166 it('true', async () => {
167 const middlewares = [stripSearchParams(true)]
168 const router = setupTest({
169 initial: { route: '/', search: { value: 'abc' } },
170 middlewares,
171 linkSearch: { value: 'xyz' },
172 })
173 const linkSearch = await runTest(router, { root: {}, posts: {} })
174 expect(linkSearch.size).toBe(0)
175 })
176​
177 it('by value', async () => {
178 const middlewares = [stripSearchParams({ value: 'abc' })]
179 const router = setupTest({
180 initial: { route: '/', search: { value: 'abc' } },
181 middlewares,
182 linkSearch: { value: 'xyz' },
183 })
184 const linkSearch = await runTest(router, {
185 root: {},
186 posts: { value: 'xyz' },
187 })
188 expect(linkSearch.size).toBe(1)
189 })
190})