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

useMutationState.test.ts

79 lines2.1 KB

1import { createKey, sleep } from '@tanstack/query-test-utils'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { ref } from 'vue-demi'
4import { useMutation } from '../useMutation'
5import { useMutationState } from '../useMutationState'
6import { useQueryClient } from '../useQueryClient'
7​
8vi.mock(import('../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 = createKey()
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).toStrictEqual([variables])
36 })
37​
38 it('should return variables after calling mutate 2', () => {
39 const queryClient = useQueryClient()
40 queryClient.clear()
41 const key = createKey()
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).toStrictEqual(variables)
54 })
55​
56 it('should work with options getter and be reactive', async () => {
57 const key = createKey()
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).toStrictEqual([])
74​
75 keyRef.value = key[0]!
76 await vi.advanceTimersByTimeAsync(0)
77 expect(mutationState.value).toStrictEqual([variables])
78 })
79})