File size: 2,216 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { describe, expectTypeOf, test } from 'vitest'
import { sleep } from '@tanstack/query-test-utils'
import { injectMutation } from '..'
import type { Signal } from '@angular/core'

describe('Discriminated union return type', () => {
  test('data should be possibly undefined by default', () => {
    const mutation = injectMutation(() => ({
      mutationFn: () => sleep(0).then(() => 'string'),
    }))

    expectTypeOf(mutation.data).toEqualTypeOf<Signal<string | undefined>>()
  })

  test('data should be defined when mutation is success', () => {
    const mutation = injectMutation(() => ({
      mutationFn: () => sleep(0).then(() => 'string'),
    }))

    if (mutation.isSuccess()) {
      expectTypeOf(mutation.data).toEqualTypeOf<Signal<string>>()
    }
  })

  test('error should be null when mutation is success', () => {
    const mutation = injectMutation(() => ({
      mutationFn: () => sleep(0).then(() => 'string'),
    }))

    if (mutation.isSuccess()) {
      expectTypeOf(mutation.error).toEqualTypeOf<Signal<null>>()
    }
  })

  test('data should be undefined when mutation is pending', () => {
    const mutation = injectMutation(() => ({
      mutationFn: () => sleep(0).then(() => 'string'),
    }))

    if (mutation.isPending()) {
      expectTypeOf(mutation.data).toEqualTypeOf<Signal<undefined>>()
    }
  })

  test('error should be defined when mutation is error', () => {
    const mutation = injectMutation(() => ({
      mutationFn: () => sleep(0).then(() => 'string'),
    }))

    if (mutation.isError()) {
      expectTypeOf(mutation.error).toEqualTypeOf<Signal<Error>>()
    }
  })

  test('should narrow variables', () => {
    const mutation = injectMutation(() => ({
      mutationFn: (_variables: string) => sleep(0).then(() => 'string'),
    }))

    if (mutation.isIdle()) {
      expectTypeOf(mutation.variables).toEqualTypeOf<Signal<undefined>>()
    }
    if (mutation.isPending()) {
      expectTypeOf(mutation.variables).toEqualTypeOf<Signal<string>>()
    }
    if (mutation.isSuccess()) {
      expectTypeOf(mutation.variables).toEqualTypeOf<Signal<string>>()
    }
    expectTypeOf(mutation.variables).toEqualTypeOf<Signal<string | undefined>>()
  })
})