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

useMutationState.test.ts

80 lines2.1 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { ref } from 'vue-demi'
3import { 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 mutationKey = ['mutation']
21 const variables = 'foo123'
22​
23 const { mutate } = useMutation({
24 mutationKey: mutationKey,
25 mutationFn: (params: string) => sleep(0).then(() => params),
26 })
27​
28 mutate(variables)
29​
30 const mutationState = useMutationState({
31 filters: { mutationKey, 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 mutationKey = ['mutation']
42 const variables = 'bar234'
43​
44 const { mutate } = useMutation({
45 mutationKey: mutationKey,
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 keyRef = ref('useMutationStateGetter2')
58 const variables = 'foo123'
59​
60 const { mutate } = useMutation({
61 mutationKey: ['useMutationStateGetter'],
62 mutationFn: (params: string) => sleep(10).then(() => params),
63 })
64​
65 mutate(variables)
66​
67 const mutationState = useMutationState(() => ({
68 filters: { mutationKey: [keyRef.value], status: 'pending' },
69 select: (mutation) => mutation.state.variables,
70 }))
71​
72 expect(mutationState.value).toEqual([])
73​
74 keyRef.value = 'useMutationStateGetter'
75​
76 await vi.advanceTimersByTimeAsync(0)
77​
78 expect(mutationState.value).toEqual([variables])
79 })
80})