Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions packages/svelte-query/tests/useMutationState/SelectExample.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<script lang="ts">
import { QueryClient } from '@tanstack/query-core'
import {
createMutation,
setQueryClientContext,
useMutationState,
} from '../../src/index.js'
import type {
Accessor,
CreateMutationOptions,
MutationStateOptions,
} from '../../src/index.js'

let {
mutationOpts,
mutationStateOpts,
}: {
mutationOpts: Accessor<CreateMutationOptions>
mutationStateOpts: MutationStateOptions<any>
} = $props()

const queryClient = new QueryClient()
setQueryClientContext(queryClient)

const mutation = createMutation(mutationOpts)

const variables = useMutationState(mutationStateOpts)
</script>

<button onclick={() => mutation.mutate()}>mutate</button>

<div>
Variables: {JSON.stringify(variables)}
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { fireEvent, render } from '@testing-library/svelte'
import { sleep } from '@tanstack/query-test-utils'
import BaseExample from './BaseExample.svelte'
import SelectExample from './SelectExample.svelte'
import type { Mutation } from '@tanstack/query-core'

describe('useMutationState', () => {
beforeEach(() => {
Expand Down Expand Up @@ -79,6 +81,32 @@ describe('useMutationState', () => {
expect(rendered.getByText('Data: ["error"]')).toBeInTheDocument()
})

test('should return selected value when using select option', async () => {
const mutationKey = ['select']

const rendered = render(SelectExample, {
props: {
mutationOpts: () => ({
mutationKey,
mutationFn: () => sleep(10).then(() => 'data'),
}),
mutationStateOpts: {
filters: { mutationKey },
select: (mutation: Mutation) => mutation.state.status,
},
},
})

expect(rendered.getByText('Variables: []')).toBeInTheDocument()

fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
await vi.advanceTimersByTimeAsync(0)
expect(rendered.getByText('Variables: ["pending"]')).toBeInTheDocument()

await vi.advanceTimersByTimeAsync(10)
expect(rendered.getByText('Variables: ["success"]')).toBeInTheDocument()
})

test('Can select specific mutation using mutation key', async () => {
const successMutationFn = vi.fn(() => sleep(10).then(() => 'data'))
const errorMutationFn = vi
Expand Down
Loading