Open History to see the last commit
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})