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

useMutationState.test.tsx

114 lines2.9 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { fireEvent } from '@solidjs/testing-library'
3import { createEffect } from 'solid-js'
4import { queryKey, 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 = queryKey()
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​
60 await vi.advanceTimersByTimeAsync(150)
61 expect(rendered.getByText('count: 1')).toBeInTheDocument()
62 })
63​
64 it('should return variables after calling mutate', async () => {
65 const variables: Array<Array<unknown>> = []
66 const mutationKey = queryKey()
67​
68 function Variables() {
69 const states = useMutationState(() => ({
70 filters: { mutationKey, status: 'pending' },
71 select: (mutation) => mutation.state.variables,
72 }))
73​
74 createEffect(() => {
75 variables.push(states())
76 })
77​
78 return null
79 }
80​
81 function Mutate() {
82 const mutation = useMutation(() => ({
83 mutationKey,
84 mutationFn: (input: number) => sleep(150).then(() => 'data' + input),
85 }))
86​
87 return (
88 <div>
89 data: {mutation.data ?? 'null'}
90 <button onClick={() => mutation.mutate(1)}>mutate</button>
91 </div>
92 )
93 }
94​
95 function Page() {
96 return (
97 <div>
98 <Variables />
99 <Mutate />
100 </div>
101 )
102 }
103​
104 const rendered = renderWithClient(queryClient, () => <Page />)
105​
106 expect(rendered.getByText('data: null')).toBeInTheDocument()
107​
108 fireEvent.click(rendered.getByRole('button', { name: /mutate/i }))
109 await vi.advanceTimersByTimeAsync(150)
110 expect(rendered.getByText('data: data1')).toBeInTheDocument()
111​
112 expect(variables).toEqual([[], [1], []])
113 })
114})