File size: 2,053 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
import { describe, expectTypeOf, test } from 'vitest'
import { get } from 'svelte/store'
import { createQuery, queryOptions } from '../../src/index.js'
import type { OmitKeyof } from '@tanstack/query-core'
import type { CreateQueryOptions } from '../../src/index.js'

describe('createQuery', () => {
  test('TData should always be defined when initialData is provided as an object', () => {
    const query = createQuery({
      queryKey: ['key'],
      queryFn: () => ({ wow: true }),
      initialData: { wow: true },
    })

    expectTypeOf(get(query).data).toEqualTypeOf<{ wow: boolean }>()
  })

  test('TData should be defined when passed through queryOptions', () => {
    const options = queryOptions({
      queryKey: ['key'],
      queryFn: () => ({ wow: true }),
      initialData: { wow: true },
    })
    const query = createQuery(options)

    expectTypeOf(get(query).data).toEqualTypeOf<{ wow: boolean }>()
  })

  test('TData should always be defined when initialData is provided as a function which ALWAYS returns the data', () => {
    const query = createQuery({
      queryKey: ['key'],
      queryFn: () => ({ wow: true }),
      initialData: () => ({ wow: true }),
    })

    expectTypeOf(get(query).data).toEqualTypeOf<{ wow: boolean }>()
  })

  test('TData should have undefined in the union when initialData is NOT provided', () => {
    const query = createQuery({
      queryKey: ['key'],
      queryFn: () => {
        return {
          wow: true,
        }
      },
    })

    expectTypeOf(get(query).data).toEqualTypeOf<{ wow: boolean } | undefined>()
  })

  test('Allow custom hooks using CreateQueryOptions', () => {
    type Data = string

    const useCustomQuery = (
      options?: OmitKeyof<CreateQueryOptions<Data>, 'queryKey' | 'queryFn'>,
    ) => {
      return createQuery({
        ...options,
        queryKey: ['todos-key'],
        queryFn: () => Promise.resolve('data'),
      })
    }

    const query = useCustomQuery()

    expectTypeOf(get(query).data).toEqualTypeOf<Data | undefined>()
  })
})