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

useLiveQuery.test-d.ts

81 lines2.8 KB

1import { describe, expectTypeOf, it } from 'vitest'
2import { createCollection, createLiveQueryCollection, eq } from '@tanstack/db'
3import { mockSyncCollectionOptions } from '../../db/tests/utils'
4import { useLiveQuery } from '../src/useLiveQuery'
5import type { CollectionStatus } from '@tanstack/db'
6import type { OutputWithVirtual } from '../../db/tests/utils'
7import type { UseLiveQueryStatus } from '../src/index'
8​
9type Person = { id: string; name: string; age: number }
10​
11const people = createCollection(
12 mockSyncCollectionOptions<Person>({
13 id: `type-people`,
14 getKey: (person) => person.id,
15 initialData: [],
16 }),
18​
19describe(`useLiveQuery types`, () => {
20 it(`types an always-enabled query callback`, () => {
21 const result = useLiveQuery((q) =>
22 q
23 .from({ person: people })
24 .select(({ person }) => ({ id: person.id, name: person.name })),
25 )
26 expectTypeOf(result.data).toMatchTypeOf<
27 Array<OutputWithVirtual<{ id: string; name: string }>>
28 >()
29 expectTypeOf(result.status).toEqualTypeOf<CollectionStatus>()
30 expectTypeOf(result.isEnabled).toEqualTypeOf<true>()
31 })
32​
33 it(`types a callback that can disable the query`, () => {
34 const enabled = null as unknown as boolean
35 const result = useLiveQuery((q) =>
36 enabled ? q.from({ person: people }) : undefined,
37 )
38 expectTypeOf(result.data).toMatchTypeOf<
39 Array<OutputWithVirtual<Person>> | undefined
40 >()
41 expectTypeOf(result.state).toMatchTypeOf<
42 ReadonlyMap<string | number, OutputWithVirtual<Person>> | undefined
43 >()
44 // A disabled query has no data, so the result must be narrowed first.
45 // @ts-expect-error data can be undefined
46 result.data.map((person) => person.id)
47 expectTypeOf(result.status).toEqualTypeOf<UseLiveQueryStatus>()
48 expectTypeOf(result.isEnabled).toEqualTypeOf<boolean>()
49 })
50​
51 it(`types findOne as one row or undefined`, () => {
52 const result = useLiveQuery((q) =>
53 q
54 .from({ person: people })
55 .where(({ person }) => eq(person.id, `1`))
56 .findOne(),
57 )
58 expectTypeOf(result.data).toMatchTypeOf<
59 OutputWithVirtual<Person> | undefined
60 >()
61 })
62​
63 it(`types the config-object form`, () => {
64 const result = useLiveQuery({
65 query: (q) => q.from({ person: people }),
66 gcTime: 1000,
67 })
68 expectTypeOf(result.data).toMatchTypeOf<Array<OutputWithVirtual<Person>>>()
69 })
70​
71 it(`types a supplied live-query Collection`, () => {
72 const adults = createLiveQueryCollection((q) =>
73 q.from({ person: people }).select(({ person }) => ({ id: person.id })),
74 )
75 const result = useLiveQuery(adults)
76 expectTypeOf(result.data).toMatchTypeOf<
77 Array<OutputWithVirtual<{ id: string }>>
78 >()
79 expectTypeOf(result.isEnabled).toEqualTypeOf<true>()
80 })
81})