Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: add tests for dependency collection #2140

Merged
merged 2 commits into from
Aug 31, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 () => {
promer94 marked this conversation as resolved.
Show resolved Hide resolved
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",
},
]
`)
})
})