Skip to content

Commit

Permalink
add test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
shuding committed May 16, 2022
1 parent 8aa5daa commit 77612b4
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
13 changes: 13 additions & 0 deletions test/type/mutator.ts
@@ -1,4 +1,5 @@
import { Equal, Expect } from '@type-challenges/utils'
import useSWR from 'swr'

import {
MutatorFn,
Expand Down Expand Up @@ -54,3 +55,15 @@ export type TestCasesForMutator = [
Expect<Equal<MutatorWrapper<Case5<{}>>, never>>,
Expect<Equal<MutatorWrapper<Case6<{}>>, Promise<{} | undefined>>>
]

export function useMutatorTypes() {
const { mutate } = useSWR<string>('')

mutate(async () => '1')

// @ts-expect-error
mutate(async () => 1)

// FIXME: this should work.
// mutate(async () => 1, { populateCache: false })
}
39 changes: 35 additions & 4 deletions test/use-swr-local-mutation.test.tsx
Expand Up @@ -1039,7 +1039,7 @@ describe('useSWR - local mutation', () => {
expect(renderedData).toEqual([undefined, 'foo', 'bar', 'baz', 'foo'])
})

it('should support optimistic updates via functional `optimisticData`', async () => {
it('should support optimistic updates via function `optimisticData`', async () => {
const key = createKey()
const renderedData = []
let mutate
Expand All @@ -1058,20 +1058,20 @@ describe('useSWR - local mutation', () => {

await executeWithoutBatching(() =>
mutate(createResponse('baz', { delay: 20 }), {
optimisticData: data => 'functional_' + data
optimisticData: data => 'function_' + data
})
)
await sleep(30)
expect(renderedData).toEqual([
undefined,
'foo',
'functional_foo',
'function_foo',
'baz',
'foo'
])
})

it('should be able use mutate to manipulate data via functional `optimisticData`', async () => {
it('should be able use mutate to manipulate data via function `optimisticData`', async () => {
const key = createKey()
const renderedData = []

Expand Down Expand Up @@ -1105,6 +1105,37 @@ describe('useSWR - local mutation', () => {
expect(renderedData).toEqual([undefined, 'loading', 'final'])
})

it('should prevent race conditions with optimistic UI', async () => {
const key = createKey()
const renderedData = []
let mutate

function Page() {
const { data, mutate: boundMutate } = useSWR(key, () => Math.random(), {
refreshInterval: 10,
dedupingInterval: 0
})
mutate = boundMutate
renderedData.push(data)
return <div>data: {String(data)}</div>
}

renderWithConfig(<Page />)

await sleep(20)
await executeWithoutBatching(() =>
mutate(createResponse('end', { delay: 50 }), {
optimisticData: 'start'
})
)
await sleep(20)

// There can never be any changes during a mutation — it should be atomic.
expect(renderedData.indexOf('end') - renderedData.indexOf('start')).toEqual(
1
)
})

it('should rollback optimistic updates when mutation fails', async () => {
const key = createKey()
const renderedData = []
Expand Down

0 comments on commit 77612b4

Please sign in to comment.