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

useMutation.test-d.tsx

86 lines2.2 KB

1import { describe, expectTypeOf, it } from 'vitest'
2import { reactive } from 'vue-demi'
3import { sleep } from '@tanstack/query-test-utils'
4import { useMutation } from '../useMutation'
5​
6describe('Discriminated union return type', () => {
7 it('data should be possibly undefined by default', () => {
8 const mutation = reactive(
9 useMutation({
10 mutationFn: (params: string) => sleep(0).then(() => params),
11 }),
12 )
13​
14 expectTypeOf(mutation.data).toEqualTypeOf<string | undefined>()
15 })
16​
17 it('data should be defined when mutation is success', () => {
18 const mutation = reactive(
19 useMutation({
20 mutationFn: (params: string) => sleep(0).then(() => params),
21 }),
22 )
23​
24 if (mutation.isSuccess) {
25 expectTypeOf(mutation.data).toEqualTypeOf<string>()
26 }
27 })
28​
29 it('error should be null when mutation is success', () => {
30 const mutation = reactive(
31 useMutation({
32 mutationFn: (params: string) => sleep(0).then(() => params),
33 }),
34 )
35​
36 if (mutation.isSuccess) {
37 expectTypeOf(mutation.error).toEqualTypeOf<null>()
38 }
39 })
40​
41 it('data should be undefined when mutation is pending', () => {
42 const mutation = reactive(
43 useMutation({
44 mutationFn: (params: string) => sleep(0).then(() => params),
45 }),
46 )
47​
48 if (mutation.isPending) {
49 expectTypeOf(mutation.data).toEqualTypeOf<undefined>()
50 }
51 })
52​
53 it('error should be defined when mutation is error', () => {
54 const mutation = reactive(
55 useMutation({
56 mutationFn: (params: string) => sleep(0).then(() => params),
57 }),
58 )
59​
60 if (mutation.isError) {
61 expectTypeOf(mutation.error).toEqualTypeOf<Error>()
62 }
63 })
64​
65 it('should narrow variables', () => {
66 const mutation = reactive(
67 useMutation({
68 mutationFn: (params: string) => sleep(0).then(() => params),
69 }),
70 )
71​
72 if (mutation.isIdle) {
73 expectTypeOf(mutation.variables).toEqualTypeOf<undefined>()
74 return
75 }
76 if (mutation.isPending) {
77 expectTypeOf(mutation.variables).toEqualTypeOf<string>()
78 return
79 }
80 if (mutation.isSuccess) {
81 expectTypeOf(mutation.variables).toEqualTypeOf<string>()
82 return
83 }
84 expectTypeOf(mutation.variables).toEqualTypeOf<string>()
85 })
86})