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

dehydrateSettled.test.tsx

90 lines2.5 KB

1import { describe, expect, it } from 'vitest'
2import { noop } from '@tanstack/query-core'
3import { QueryClient } from '../QueryClient'
4import { dehydrateSettled } from '../dehydrateSettled'
5​
6const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
7​
8describe('dehydrateSettled', () => {
9 it('waits for in-flight fetches instead of snapshotting mid-fetch', async () => {
10 const client = new QueryClient()
11 // Fire-and-forget, the way loaders hint prefetches.
12 void client
13 .query({
14 queryKey: ['slow'],
15 queryFn: async () => {
16 await sleep(20)
17 return 'slow-data'
18 },
19 })
20 .catch(noop)
21​
22 const state = await dehydrateSettled(client)
23​
24 const query = state.queries.find((q) => q.queryHash === '["slow"]')
25 expect(query?.state.data).toBe('slow-data')
26 expect(query?.state.status).toBe('success')
27 })
28​
29 it('chases fetches dispatched by earlier settlements to quiescence', async () => {
30 const client = new QueryClient()
31 void client
32 .query({
33 queryKey: ['first'],
34 queryFn: async () => {
35 await sleep(10)
36 // A dependent fetch that only exists once the first one lands.
37 void client
38 .query({
39 queryKey: ['second'],
40 queryFn: async () => {
41 await sleep(10)
42 return 'second-data'
43 },
44 })
45 .catch(noop)
46 return 'first-data'
47 },
48 })
49 .catch(noop)
50​
51 const state = await dehydrateSettled(client)
52​
53 expect(state.queries.map((q) => q.queryHash).sort()).toStrictEqual([
54 '["first"]',
55 '["second"]',
56 ])
57 expect(
58 state.queries.find((q) => q.queryHash === '["second"]')?.state.data,
59 ).toBe('second-data')
60 })
61​
62 it('settles failures without rejecting and forwards dehydrate options', async () => {
63 const client = new QueryClient()
64 void client
65 .query({
66 queryKey: ['ok'],
67 queryFn: async () => {
68 await sleep(5)
69 return 'ok-data'
70 },
71 })
72 .catch(noop)
73 void client
74 .query({
75 queryKey: ['boom'],
76 retry: false,
77 queryFn: async () => {
78 await sleep(5)
79 throw new Error('nope')
80 },
81 })
82 .catch(noop)
83​
84 const state = await dehydrateSettled(client, {
85 shouldDehydrateQuery: (query) => query.state.status === 'success',
86 })
87​
88 expect(state.queries.map((q) => q.queryHash)).toStrictEqual(['["ok"]'])
89 })
90})