Open History to see the last commit
1import { describe, expectTypeOf, it } from 'vitest'
2import { renderHook } from '@solidjs/testing-library'
3import { createCollection } from '../../db/src/collection/index'
4import { mockSyncCollectionOptions } from '../../db/tests/utils'
5import { createLiveQueryCollection, eq } from '../../db/src/query/index'
6import { useLiveQuery } from '../src/useLiveQuery'
7import type { OutputWithVirtual } from '../../db/tests/utils'
8import type { SingleResult } from '../../db/src/types'
9
10type Person = {
11 id: string
12 name: string
13 age: number
14 email: string
15 isActive: boolean
16 team: string
17}
18
19describe(`useLiveQuery type assertions`, () => {
20 it(`should type findOne query builder to return a single row`, () => {
21 const collection = createCollection(
22 mockSyncCollectionOptions<Person>({
23 id: `test-persons-2`,
24 getKey: (person: Person) => person.id,
25 initialData: [],
26 }),
27 )
28
29 const rendered = renderHook(() => {
30 return useLiveQuery((q) =>
31 q
32 .from({ collection })
33 .where(({ collection: c }) => eq(c.id, `3`))
34 .findOne(),
35 )
36 })
37
38 expectTypeOf(rendered.result()).toMatchTypeOf<
39 OutputWithVirtual<Person> | undefined
40 >()
41 })
42
43 it(`should type findOne collection using createLiveQueryCollection to return a single row`, () => {
44 const collection = createCollection(
45 mockSyncCollectionOptions<Person>({
46 id: `test-persons-2`,
47 getKey: (person: Person) => person.id,
48 initialData: [],
49 }),
50 )
51
52 const liveQueryCollection = createLiveQueryCollection({
53 query: (q) =>
54 q
55 .from({ collection })
56 .where(({ collection: c }) => eq(c.id, `3`))
57 .findOne(),
58 })
59
60 expectTypeOf(liveQueryCollection).toExtend<SingleResult>()
61
62 const rendered = renderHook(() => {
63 return useLiveQuery(() => liveQueryCollection)
64 })
65
66 expectTypeOf(rendered.result()).toMatchTypeOf<
67 OutputWithVirtual<Person> | undefined
68 >()
69 })
70
71 it(`should type non-findOne queries to return an array`, () => {
72 const collection = createCollection(
73 mockSyncCollectionOptions<Person>({
74 id: `test-persons-2`,
75 getKey: (person: Person) => person.id,
76 initialData: [],
77 }),
78 )
79
80 const rendered = renderHook(() => {
81 return useLiveQuery((q) => q.from({ collection }))
82 })
83
84 expectTypeOf(rendered.result()).toMatchTypeOf<
85 Array<OutputWithVirtual<Person>>
86 >()
87 })
88})