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

createQuery.test.ts

64 lines1.9 KB

1import { describe, it, expect } from 'vitest'
2import { render, waitFor } from '@testing-library/svelte'
3import { writable } from 'svelte/store'
4import CreateQuery from './CreateQuery.svelte'
5import { sleep } from './utils'
6import type { CreateQueryOptions, WritableOrVal } from '../types'
7​
8describe('createQuery', () => {
9 it('Render and wait for success', async () => {
10 const rendered = render(CreateQuery, {
11 props: {
12 options: {
13 queryKey: ['test'],
14 queryFn: async () => {
15 await sleep(10)
16 return 'Success'
17 },
18 },
19 },
20 })
21​
22 await waitFor(() => {
23 expect(rendered.getByText('Loading')).toBeInTheDocument()
24 })
25​
26 await waitFor(() => {
27 expect(rendered.getByText('Success')).toBeInTheDocument()
28 })
29 })
30​
31 it('should keep previous data when returned as placeholder data', async () => {
32 const options: WritableOrVal<CreateQueryOptions> = writable({
33 queryKey: ['test', [1]],
34 queryFn: async ({ queryKey }) => {
35 await sleep(50)
36 const ids = queryKey[1]
37 if (!ids || !Array.isArray(ids)) return []
38 return ids.map((id) => ({ id }))
39 },
40 placeholderData: (previousData: { id: number }[]) => previousData,
41 })
42 const rendered = render(CreateQuery, { props: { options } })
43​
44 expect(rendered.queryByText('id: 1')).not.toBeInTheDocument()
45 expect(rendered.queryByText('id: 2')).not.toBeInTheDocument()
46​
47 await sleep(100)
48​
49 expect(rendered.queryByText('id: 1')).toBeInTheDocument()
50 expect(rendered.queryByText('id: 2')).not.toBeInTheDocument()
51​
52 options.update((o) => ({ ...o, queryKey: ['test', [1, 2]] }))
53​
54 await sleep(0)
55​
56 expect(rendered.queryByText('id: 1')).toBeInTheDocument()
57 expect(rendered.queryByText('id: 2')).not.toBeInTheDocument()
58​
59 await sleep(100)
60​
61 expect(rendered.queryByText('id: 1')).toBeInTheDocument()
62 expect(rendered.queryByText('id: 2')).toBeInTheDocument()
63 })
64})