Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useMutationState.test.tsx

90 lines2.4 KB

1import { describe, expect, expectTypeOf, it } from 'vitest'
2import { fireEvent, render, waitFor } from '@solidjs/testing-library'
3import { createEffect } from 'solid-js'
4import { useMutationState } from '../useMutationState'
5import { createMutation } from '../createMutation'
6import { QueryClientProvider } from '../QueryClientProvider'
7import { createQueryClient, doNotExecute, sleep } from './utils'
8import type { MutationState, MutationStatus } from '@tanstack/query-core'
9​
10describe('useMutationState', () => {
11 describe('types', () => {
12 it('should default to QueryState', () => {
13 doNotExecute(() => {
14 const result = useMutationState(() => ({
15 filters: { status: 'pending' },
16 }))
17​
18 expectTypeOf<Array<MutationState>>(result())
19 })
20 })
21 it('should infer with select', () => {
22 doNotExecute(() => {
23 const result = useMutationState(() => ({
24 filters: { status: 'pending' },
25 select: (mutation) => mutation.state.status,
26 }))
27​
28 expectTypeOf<Array<MutationStatus>>(result())
29 })
30 })
31 })
32 it('should return variables after calling mutate', async () => {
33 const queryClient = createQueryClient()
34 const variables: Array<Array<unknown>> = []
35 const mutationKey = ['mutation']
36​
37 function Variables() {
38 const states = useMutationState(() => ({
39 filters: { mutationKey, status: 'pending' },
40 select: (mutation) => mutation.state.variables,
41 }))
42​
43 createEffect(() => {
44 variables.push(states())
45 })
46​
47 return null
48 }
49​
50 function Mutate() {
51 const mutation = createMutation(() => ({
52 mutationKey,
53 mutationFn: async (input: number) => {
54 await sleep(150)
55 return 'data' + input
56 },
57 }))
58​
59 return (
60 <div>
61 data: {mutation.data ?? 'null'}
62 <button onClick={() => mutation.mutate(1)}>mutate</button>
63 </div>
64 )
65 }
66​
67 function Page() {
68 return (
69 <div>
70 <Variables />
71 <Mutate />
72 </div>
73 )
74 }
75​
76 const rendered = render(() => (
77 <QueryClientProvider client={queryClient}>
78 <Page />
79 </QueryClientProvider>
80 ))
81​
82 await waitFor(() => rendered.getByText('data: null'))
83​
84 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
85​
86 await waitFor(() => rendered.getByText('data: data1'))
87​
88 expect(variables).toEqual([[], [1], []])
89 })
90})