Open History to see the last commit
1import { queryKey } from '@tanstack/query-test-utils'
2import { act } from '@testing-library/preact'
3import { hydrate as preactHydrate, render } from 'preact'
4import type { VNode } from 'preact'
5import { renderToString } from 'preact-render-to-string'
6import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
7β
8import {
9 QueryCache,
10 QueryClient,
11 QueryClientProvider,
12 dehydrate,
13 hydrate,
14 useQuery,
15} from '..'
16import { setIsServer } from './utils'
17β
18const PreactHydrate = (element: VNode, container: Element) => {
19 act(() => {
20 preactHydrate(element, container)
21 })
22 // To unmount in Preact, you render null into the same container
23 return () => {
24 act(() => {
25 render(null, container)
26 })
27 }
28}
29β
30async function fetchData<TData>(value: TData, ms?: number): Promise<TData> {
31 await vi.advanceTimersByTimeAsync(ms || 1)
32 return value
33}
34β
35function PrintStateComponent({ componentName, result }: any): any {
36 return `${componentName} - status:${result.status} fetching:${result.isFetching} data:${result.data}`
37}
38β
39describe('Server side rendering with de/rehydration', () => {
40 const successKey = queryKey()
41 const errorKey = queryKey()
42β
43 beforeAll(() => {
44 vi.useFakeTimers()
45 })
46β
47 afterAll(() => {
48 vi.useRealTimers()
49 })
50β
51 it('should not mismatch on success', async () => {
52 const consoleMock = vi.spyOn(console, 'error')
53 consoleMock.mockImplementation(() => undefined)
54β
55 const fetchDataSuccess = vi.fn<typeof fetchData>(fetchData)
56β
57 // -- Shared part --
58 function SuccessComponent() {
59 const result = useQuery({
60 queryKey: successKey,
61 queryFn: () => fetchDataSuccess('success!'),
62 })
63 return (
64 <PrintStateComponent componentName="SuccessComponent" result={result} />
65 )
66 }
67β
68 // -- Server part --
69 setIsServer(true)
70β
71 const prefetchCache = new QueryCache()
72 const prefetchClient = new QueryClient({
73 queryCache: prefetchCache,
74 })
75 await prefetchClient.prefetchQuery({
76 queryKey: successKey,
77 queryFn: () => fetchDataSuccess('success'),
78 })
79 const dehydratedStateServer = dehydrate(prefetchClient)
80 const renderCache = new QueryCache()
81 const renderClient = new QueryClient({
82 queryCache: renderCache,
83 })
84 hydrate(renderClient, dehydratedStateServer)
85 const markup = renderToString(
86 <QueryClientProvider client={renderClient}>
87 <SuccessComponent />
88 </QueryClientProvider>,
89 )
90 const stringifiedState = JSON.stringify(dehydratedStateServer)
91 renderClient.clear()
92 setIsServer(false)
93β
94 const expectedMarkup =
95 'SuccessComponent - status:success fetching:true data:success'
96β
97 expect(markup).toBe(expectedMarkup)
98 expect(fetchDataSuccess).toHaveBeenCalledTimes(1)
99β
100 // -- Client part --
101 const el = document.createElement('div')
102 el.innerHTML = markup
103β
104 const queryCache = new QueryCache()
105 const queryClient = new QueryClient({ queryCache })
106 hydrate(queryClient, JSON.parse(stringifiedState))
107β
108 const unmount = PreactHydrate(
109 <QueryClientProvider client={queryClient}>
110 <SuccessComponent />
111 </QueryClientProvider>,
112 el,
113 )
114β
115 // Check that we have no React hydration mismatches
116 expect(consoleMock).toHaveBeenCalledTimes(0)
117β
118 expect(fetchDataSuccess).toHaveBeenCalledTimes(2)
119 expect(el.innerHTML).toBe(expectedMarkup)
120β
121 unmount()
122 queryClient.clear()
123 consoleMock.mockRestore()
124 })
125β
126 it('should not mismatch on error', async () => {
127 const consoleMock = vi.spyOn(console, 'error')
128 consoleMock.mockImplementation(() => undefined)
129β
130 const fetchDataError = vi.fn(() => {
131 throw new Error('fetchDataError')
132 })
133β
134 // -- Shared part --
135 function ErrorComponent() {
136 const result = useQuery({
137 queryKey: errorKey,
138 queryFn: () => fetchDataError(),
139 retry: false,
140 })
141 return (
142 <PrintStateComponent componentName="ErrorComponent" result={result} />
143 )
144 }
145β
146 // -- Server part --
147 setIsServer(true)
148 const prefetchCache = new QueryCache()
149 const prefetchClient = new QueryClient({
150 queryCache: prefetchCache,
151 })
152 await prefetchClient.prefetchQuery({
153 queryKey: errorKey,
154 queryFn: () => fetchDataError(),
155 })
156 const dehydratedStateServer = dehydrate(prefetchClient)
157 const renderCache = new QueryCache()
158 const renderClient = new QueryClient({
159 queryCache: renderCache,
160 })
161 hydrate(renderClient, dehydratedStateServer)
162 const markup = renderToString(
163 <QueryClientProvider client={renderClient}>
164 <ErrorComponent />
165 </QueryClientProvider>,
166 )
167 const stringifiedState = JSON.stringify(dehydratedStateServer)
168 renderClient.clear()
169 setIsServer(false)
170β
171 const expectedMarkup =
172 'ErrorComponent - status:pending fetching:true data:undefined'
173β
174 expect(markup).toBe(expectedMarkup)
175β
176 // -- Client part --
177 const el = document.createElement('div')
178 el.innerHTML = markup
179β
180 const queryCache = new QueryCache()
181 const queryClient = new QueryClient({ queryCache })
182 hydrate(queryClient, JSON.parse(stringifiedState))
183β
184 const unmount = PreactHydrate(
185 <QueryClientProvider client={queryClient}>
186 <ErrorComponent />
187 </QueryClientProvider>,
188 el,
189 )
190β
191 expect(consoleMock).toHaveBeenCalledTimes(0)
192 expect(fetchDataError).toHaveBeenCalledTimes(2)
193 expect(el.innerHTML).toBe(expectedMarkup)
194 await vi.advanceTimersByTimeAsync(50)
195 expect(fetchDataError).toHaveBeenCalledTimes(2)
196 expect(el.innerHTML).toBe(
197 'ErrorComponent - status:error fetching:false data:undefined',
198 )
199β
200 unmount()
201 queryClient.clear()
202 consoleMock.mockRestore()
203 })
204β
205 it('should not mismatch on queries that were not prefetched', async () => {
206 const consoleMock = vi.spyOn(console, 'error')
207 consoleMock.mockImplementation(() => undefined)
208β
209 const fetchDataSuccess = vi.fn<typeof fetchData>(fetchData)
210β
211 // -- Shared part --
212 function SuccessComponent() {
213 const result = useQuery({
214 queryKey: successKey,
215 queryFn: () => fetchDataSuccess('success!'),
216 })
217 return (
218 <PrintStateComponent componentName="SuccessComponent" result={result} />
219 )
220 }
221β
222 // -- Server part --
223 setIsServer(true)
224β
225 const prefetchClient = new QueryClient()
226 const dehydratedStateServer = dehydrate(prefetchClient)
227 const renderClient = new QueryClient()
228 hydrate(renderClient, dehydratedStateServer)
229 const markup = renderToString(
230 <QueryClientProvider client={renderClient}>
231 <SuccessComponent />
232 </QueryClientProvider>,
233 )
234 const stringifiedState = JSON.stringify(dehydratedStateServer)
235 renderClient.clear()
236 setIsServer(false)
237β
238 const expectedMarkup =
239 'SuccessComponent - status:pending fetching:true data:undefined'
240β
241 expect(markup).toBe(expectedMarkup)
242β
243 // -- Client part --
244 const el = document.createElement('div')
245 el.innerHTML = markup
246β
247 const queryCache = new QueryCache()
248 const queryClient = new QueryClient({ queryCache })
249 hydrate(queryClient, JSON.parse(stringifiedState))
250β
251 const unmount = PreactHydrate(
252 <QueryClientProvider client={queryClient}>
253 <SuccessComponent />
254 </QueryClientProvider>,
255 el,
256 )
257β
258 // Check that we have no React hydration mismatches
259 expect(consoleMock).toHaveBeenCalledTimes(0)
260 expect(fetchDataSuccess).toHaveBeenCalledTimes(1)
261 expect(el.innerHTML).toBe(expectedMarkup)
262 await vi.advanceTimersByTimeAsync(50)
263 expect(fetchDataSuccess).toHaveBeenCalledTimes(1)
264 expect(el.innerHTML).toBe(
265 'SuccessComponent - status:success fetching:false data:success!',
266 )
267β
268 unmount()
269 queryClient.clear()
270 consoleMock.mockRestore()
271 })
272})