forked from vercel/swr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-swr-streaming-ssr.test.tsx
More file actions
85 lines (71 loc) · 2.41 KB
/
use-swr-streaming-ssr.test.tsx
File metadata and controls
85 lines (71 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { act } from '@testing-library/react'
import { Suspense } from 'react'
import useSWR from 'swr'
import {
createKey,
createResponse,
renderWithConfig,
hydrateWithConfig,
mockConsoleForHydrationErrors,
sleep
} from './utils'
describe('useSWR - streaming', () => {
afterEach(() => {
jest.clearAllMocks()
jest.restoreAllMocks()
})
it('should match ssr result when hydrating', async () => {
const ensureAndUnmock = mockConsoleForHydrationErrors()
const key = createKey()
// A block fetches the data and updates the cache.
function Block() {
const { data } = useSWR(key, () => createResponse('SWR', { delay: 10 }))
return <div>{data || 'undefined'}</div>
}
const container = document.createElement('div')
container.innerHTML = '<div>undefined</div>'
await hydrateWithConfig(<Block />, container)
ensureAndUnmock()
})
// NOTE: this test is failing because it's not possible to test this behavior
// in JSDOM. We need to test this in a real browser.
it.failing(
'should match the ssr result when streaming and partially hydrating',
async () => {
const key = createKey()
const dataDuringHydration = {}
// A block fetches the data and updates the cache.
function Block({ suspense, delay, id }) {
const { data } = useSWR(key, () => createResponse('SWR', { delay }), {
suspense
})
// The first render is always hydration in our case.
if (!dataDuringHydration[id]) {
dataDuringHydration[id] = data || 'undefined'
}
return <div>{data || 'undefined'}</div>
}
// In this example, a will be hydrated first and b will still be streamed.
// When a is hydrated, it will update the client cache to SWR, and when
// b is being hydrated, it should NOT read that cache.
renderWithConfig(
<>
<Block id="a" suspense={false} delay={10} />
<Suspense fallback={null}>
<Block id="b" suspense={true} delay={20} />
</Suspense>
</>
)
// The SSR result will always be 2 undefined values because data fetching won't
// happen on the server:
// <div>undefined</div>
// <div>undefined</div>
// Wait for streaming to finish.
await act(() => sleep(50))
expect(dataDuringHydration).toEqual({
a: 'undefined',
b: 'undefined'
})
}
)
})