Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { ref } from 'vue-demi'
3import { queryKey, sleep } from '@tanstack/query-test-utils'
4import { useMutation } from '../useMutation'
5import { useMutationState } from '../useMutationState'
6import { useQueryClient } from '../useQueryClient'
7β
8vi.mock('../useQueryClient')
9β
10describe('useMutationState', () => {
11 beforeEach(() => {
12 vi.useFakeTimers()
13 })
14β
15 afterEach(() => {
16 vi.useRealTimers()
17 })
18β
19 it('should return variables after calling mutate 1', () => {
20 const key = queryKey()
21 const variables = 'foo123'
22β
23 const { mutate } = useMutation({
24 mutationKey: key,
25 mutationFn: (params: string) => sleep(0).then(() => params),
26 })
27β
28 mutate(variables)
29β
30 const mutationState = useMutationState({
31 filters: { mutationKey: key, status: 'pending' },
32 select: (mutation) => mutation.state.variables,
33 })
34β
35 expect(mutationState.value).toEqual([variables])
36 })
37β
38 it('should return variables after calling mutate 2', () => {
39 const queryClient = useQueryClient()
40 queryClient.clear()
41 const key = queryKey()
42 const variables = 'bar234'
43β
44 const { mutate } = useMutation({
45 mutationKey: key,
46 mutationFn: (params: string) => sleep(0).then(() => params),
47 })
48β
49 mutate(variables)
50β
51 const mutationState = useMutationState()
52β
53 expect(mutationState.value[0]?.variables).toEqual(variables)
54 })
55β
56 it('should work with options getter and be reactive', async () => {
57 const key = queryKey()
58 const keyRef = ref('useMutationStateGetter2')
59 const variables = 'foo123'
60β
61 const { mutate } = useMutation({
62 mutationKey: key,
63 mutationFn: (params: string) => sleep(10).then(() => params),
64 })
65β
66 mutate(variables)
67β
68 const mutationState = useMutationState(() => ({
69 filters: { mutationKey: [keyRef.value], status: 'pending' },
70 select: (mutation) => mutation.state.variables,
71 }))
72β
73 expect(mutationState.value).toEqual([])
74β
75 keyRef.value = key[0]!
76 await vi.advanceTimersByTimeAsync(0)
77 expect(mutationState.value).toEqual([variables])
78 })
79})