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

useMutationState.test.tsx

113 lines2.9 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { fireEvent } from '@solidjs/testing-library'
3import { createEffect } from 'solid-js'
4import { createKey, sleep } from '@tanstack/query-test-utils'
5import { QueryClient, useMutation, useMutationState } from '..'
6import { renderWithClient } from './utils'
7​
8describe('useMutationState', () => {
9 let queryClient: QueryClient
10​
11 beforeEach(() => {
12 vi.useFakeTimers()
13 queryClient = new QueryClient()
14 })
15​
16 afterEach(() => {
17 queryClient.clear()
18 vi.useRealTimers()
19 })
20​
21 it('should return all mutation states when called without options', async () => {
22 const mutationKey = createKey()
23​
24 function States() {
25 const mutationStates = useMutationState()
26​
27 return <div>count: {mutationStates().length}</div>
28 }
29​
30 function Mutate() {
31 const mutation = useMutation(() => ({
32 mutationKey,
33 mutationFn: (input: number) => sleep(150).then(() => `data${input}`),
34 }))
35​
36 return (
37 <div>
38 <button onClick={() => mutation.mutate(1)}>mutate</button>
39 </div>
40 )
41 }
42​
43 function Page() {
44 return (
45 <div>
46 <States />
47 <Mutate />
48 </div>
49 )
50 }
51​
52 const rendered = renderWithClient(queryClient, () => <Page />)
53​
54 expect(rendered.getByText('count: 0')).toBeInTheDocument()
55​
56 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
57 await vi.advanceTimersByTimeAsync(0)
58 expect(rendered.getByText('count: 1')).toBeInTheDocument()
59 await vi.advanceTimersByTimeAsync(150)
60 expect(rendered.getByText('count: 1')).toBeInTheDocument()
61 })
62​
63 it('should return variables after calling mutate', async () => {
64 const variables: Array<Array<unknown>> = []
65 const mutationKey = createKey()
66​
67 function Variables() {
68 const states = useMutationState(() => ({
69 filters: { mutationKey, status: 'pending' },
70 select: (mutation) => mutation.state.variables,
71 }))
72​
73 createEffect(() => {
74 variables.push(states())
75 })
76​
77 return null
78 }
79​
80 function Mutate() {
81 const mutation = useMutation(() => ({
82 mutationKey,
83 mutationFn: (input: number) => sleep(150).then(() => `data${input}`),
84 }))
85​
86 return (
87 <div>
88 data: {mutation.data ?? 'null'}
89 <button onClick={() => mutation.mutate(1)}>mutate</button>
90 </div>
91 )
92 }
93​
94 function Page() {
95 return (
96 <div>
97 <Variables />
98 <Mutate />
99 </div>
100 )
101 }
102​
103 const rendered = renderWithClient(queryClient, () => <Page />)
104​
105 expect(rendered.getByText('data: null')).toBeInTheDocument()
106​
107 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
108 await vi.advanceTimersByTimeAsync(150)
109 expect(rendered.getByText('data: data1')).toBeInTheDocument()
110​
111 expect(variables).toStrictEqual([[], [1], []])
112 })
113})