Skip to content

Commit

Permalink
test(svelte-query): add refetch test for createQuery (#7810)
Browse files Browse the repository at this point in the history
  • Loading branch information
lachlancollins authored Jul 28, 2024
1 parent 99f1250 commit 461876a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
32 changes: 32 additions & 0 deletions packages/svelte-query/tests/createQuery/RefetchExample.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<script lang="ts">
import { QueryClient } from '@tanstack/query-core'
import { derived, writable } from 'svelte/store'
import { createQuery } from '../../src/createQuery'
import { sleep } from '../utils'
import type { QueryObserverResult } from '@tanstack/query-core'
import type { Writable } from 'svelte/store'
export let states: Writable<Array<QueryObserverResult>>
const queryClient = new QueryClient()
const count = writable(0)
const options = derived(count, ($count) => ({
queryKey: ['test'],
queryFn: async () => {
await sleep(5)
return ++$count
},
}))
const query = createQuery(options, queryClient)
$: states.update((prev) => [...prev, $query])
</script>

<button on:click={() => queryClient.removeQueries({ queryKey: ['test'] })}
>Remove</button
>
<button on:click={() => $query.refetch()}>Refetch</button>

<div>Data: {$query.data ?? 'undefined'}</div>
31 changes: 31 additions & 0 deletions packages/svelte-query/tests/createQuery/createQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { sleep } from '../utils'
import BaseExample from './BaseExample.svelte'
import DisabledExample from './DisabledExample.svelte'
import PlaceholderData from './PlaceholderData.svelte'
import RefetchExample from './RefetchExample.svelte'
import type { Writable } from 'svelte/store'
import type { QueryObserverResult } from '@tanstack/query-core'

Expand Down Expand Up @@ -387,4 +388,34 @@ describe('createQuery', () => {
isSuccess: false,
})
})

test('Create a new query when refetching a removed query', async () => {
const statesStore: Writable<Array<QueryObserverResult>> = writable([])

const rendered = render(RefetchExample, {
props: {
states: statesStore,
},
})

await waitFor(() => rendered.getByText('Data: 1'))
fireEvent.click(rendered.getByRole('button', { name: /Remove/i }))

await sleep(5)

fireEvent.click(rendered.getByRole('button', { name: /Refetch/i }))
await waitFor(() => rendered.getByText('Data: 2'))

const states = get(statesStore)

expect(states.length).toBe(4)
// Initial
expect(states[0]).toMatchObject({ data: undefined, dataUpdatedAt: 0 })
// Fetched
expect(states[1]).toMatchObject({ data: 1 })
// Switch
expect(states[2]).toMatchObject({ data: undefined, dataUpdatedAt: 0 })
// Fetched
expect(states[3]).toMatchObject({ data: 2 })
})
})

0 comments on commit 461876a

Please sign in to comment.