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

suspense.test.ts

81 lines2.8 KB

1/**
2 * Suspense + error-boundary integration: a `suspense: true` query throws its
3 * in-flight promise (caught by octane's `@pending`) and, on error, throws the
4 * error (caught by `@catch`) — the octane equivalents of React Suspense /
5 * ErrorBoundary.
6 */
7import { beforeEach, describe, expect, it } from 'vitest'
8import { QueryClient } from '@tanstack/octane-query'
9import { mount, nextPaint } from '../_helpers'
10import {
11 SuspenseApp,
12 SuspenseComponentApp,
13 SuspenseQueriesApp,
14} from '../_fixtures/suspense.tsrx'
15​
16let client: QueryClient
17beforeEach(() => {
18 client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
19 client.mount()
20})
21​
22async function flush() {
23 for (let i = 0; i < 6; i++) {
24 await new Promise((r) => setTimeout(r, 0))
25 await nextPaint()
26 }
28​
29describe('suspense query', () => {
30 it('shows @pending while loading, then the data', async () => {
31 let resolveFn: (v: string) => void = () => {}
32 const queryFn = () => new Promise<string>((res) => (resolveFn = res))
33 const r = mount(SuspenseApp, { client, queryFn })
34 // First render suspends → @pending fallback.
35 expect(r.find('#fallback').textContent).toBe('loading')
36 await flush()
37 resolveFn('ready')
38 await flush()
39 expect(r.find('#data').textContent).toBe('data:ready')
40 r.unmount()
41 })
42​
43 it('shows @catch when the suspense query errors', async () => {
44 let rejectFn: (e: Error) => void = () => {}
45 const queryFn = () => new Promise<string>((_res, rej) => (rejectFn = rej))
46 const r = mount(SuspenseApp, { client, queryFn })
47 expect(r.find('#fallback').textContent).toBe('loading')
48 await flush()
49 rejectFn(new Error('nope'))
50 await flush()
51 expect(r.find('#caught').textContent).toBe('caught:nope')
52 r.unmount()
53 })
54​
55 it('works with octane’s <Suspense> component (not just @try)', async () => {
56 let resolveFn: (v: string) => void = () => {}
57 const queryFn = () => new Promise<string>((res) => (resolveFn = res))
58 const r = mount(SuspenseComponentApp, { client, queryFn })
59 expect(r.find('#fallback').textContent).toBe('loading')
60 await flush()
61 resolveFn('ready')
62 await flush()
63 expect(r.find('#data').textContent).toBe('data:ready')
64 r.unmount()
65 })
66​
67 it('supports useSuspenseQueries for multiple suspense queries', async () => {
68 let resolveA: (v: string) => void = () => {}
69 let resolveB: (v: string) => void = () => {}
70 const a = () => new Promise<string>((res) => (resolveA = res))
71 const b = () => new Promise<string>((res) => (resolveB = res))
72 const r = mount(SuspenseQueriesApp, { client, a, b })
73 expect(r.find('#fallback').textContent).toBe('loading')
74 await flush()
75 resolveA('A')
76 resolveB('B')
77 await flush()
78 expect(r.find('#data').textContent).toBe('data:A/B')
79 r.unmount()
80 })
81})