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

useMutationState.test.tsx

79 lines1.8 KB

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