Skip to content

Commit 6a07522

Browse files
authored
test: add a test for useSWRInfinite with initialData (#894)
1 parent b41b3be commit 6a07522

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

test/use-swr-infinite.test.tsx

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,4 +463,52 @@ describe('useSWRInfinite', () => {
463463
await act(() => new Promise(res => setTimeout(res, 10)))
464464
expect(container.textContent).toMatchInlineSnapshot(`"${cachedData}"`)
465465
})
466+
467+
it('should re-use initialData', async () => {
468+
const dummyResponses = {
469+
'/api?page=1': ['page-1-1', 'page-1-2'],
470+
'/api?page=2': ['page-2-1', 'page-2-2']
471+
}
472+
let requests = []
473+
474+
function Page() {
475+
const { data, size, setSize } = useSWRInfinite<string[], string>(
476+
index => {
477+
return [`page-test-10`, `/api?page=${index + 1}`]
478+
},
479+
async (_, index) => {
480+
await new Promise(res => setTimeout(res, 100))
481+
requests.push(index)
482+
return dummyResponses[index]
483+
},
484+
{
485+
initialData: [dummyResponses[`/api?page=1`]]
486+
}
487+
)
488+
489+
return (
490+
<div
491+
onClick={() => {
492+
// load next page
493+
setSize(size + 1)
494+
}}
495+
>
496+
{(data ? [].concat(...data) : []).join(', ')}
497+
</div>
498+
)
499+
}
500+
501+
const { container } = render(<Page />)
502+
503+
// render with the initialData
504+
expect(container.textContent).toMatchInlineSnapshot(`"page-1-1, page-1-2"`)
505+
expect(requests).toEqual([]) // should use the initial data
506+
fireEvent.click(container.firstElementChild)
507+
await waitForDomChange({ container })
508+
// Should this reuse the cached data for `page=1`?
509+
expect(requests).toEqual(['/api?page=1', '/api?page=2'])
510+
expect(container.textContent).toMatchInlineSnapshot(
511+
`"page-1-1, page-1-2, page-2-1, page-2-2"`
512+
)
513+
})
466514
})

0 commit comments

Comments
 (0)