Skip to content

Commit

Permalink
test: add tests for dependency collection (#2140)
Browse files Browse the repository at this point in the history
  • Loading branch information
koba04 committed Aug 31, 2022
1 parent 06923e8 commit 993e035
Showing 1 changed file with 99 additions and 0 deletions.
99 changes: 99 additions & 0 deletions test/use-swr-integration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -470,4 +470,103 @@ describe('useSWR', () => {
await act(() => sleep(150))
expect(count).toBe(2)
})

// Test for https://swr.vercel.app/docs/advanced/performance#dependency-collection
it('should render four times in the worst case', async () => {
let isFirstFetch = true
const fetcher = async () => {
if (isFirstFetch) {
isFirstFetch = false
throw new Error('error')
}
return 'value'
}
const key = createKey()

const logs = []

function Page() {
const { data, error, isLoading, isValidating } = useSWR(key, fetcher, {
errorRetryInterval: 10
})
logs.push({
data,
error,
isLoading,
isValidating
})
if (isLoading) return <p>loading</p>
return <p>data:{data}</p>
}

renderWithConfig(<Page />)
await screen.findByText('data:value')

expect(logs).toMatchInlineSnapshot(`
Array [
Object {
"data": undefined,
"error": undefined,
"isLoading": true,
"isValidating": true,
},
Object {
"data": undefined,
"error": [Error: error],
"isLoading": false,
"isValidating": false,
},
Object {
"data": undefined,
"error": [Error: error],
"isLoading": true,
"isValidating": true,
},
Object {
"data": "value",
"error": undefined,
"isLoading": false,
"isValidating": false,
},
]
`)
})

// Test for https://swr.vercel.app/docs/advanced/performance#dependency-collection
it('should render only two times in the best case', async () => {
let isFirstFetch = true
const fetcher = async () => {
if (isFirstFetch) {
isFirstFetch = false
throw new Error('error')
}
return 'value'
}
const key = createKey()

const logs = []

function Page() {
const { data } = useSWR(key, fetcher, {
errorRetryInterval: 10
})
logs.push({ data })
if (!data) return <p>loading</p>
return <p>data:{data}</p>
}

renderWithConfig(<Page />)
await screen.findByText('data:value')

expect(logs).toMatchInlineSnapshot(`
Array [
Object {
"data": undefined,
},
Object {
"data": "value",
},
]
`)
})
})

0 comments on commit 993e035

Please sign in to comment.