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

searchMiddleware.test.tsx

178 lines5.1 KB

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