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

testing.md

240 lines7.3 KB

1---
2id: testing
3title: Testing
4---
5​
6Svelte Query works by means of functions like `createQuery`, either the ones we offer or custom ones that wrap around them. They read the `QueryClient` from the Svelte context that `QueryClientProvider` sets, or from the `QueryClient` accessor you pass as their last argument.
7​
8Following the [testing guide](https://svelte.dev/docs/svelte/testing) of the Svelte docs, you can test these functions inside `$effect.root` in a `.svelte.test.ts` file, and test components with [Svelte Testing Library](https://testing-library.com/docs/svelte-testing-library/intro/).
9​
10## Setup
11​
12Install Vitest, jsdom, and Svelte Testing Library by running:
13​
14```sh
15npm install vitest jsdom @testing-library/svelte @testing-library/jest-dom --save-dev
16```
17​
18Then add the `svelteTesting` plugin and a setup file for the `jest-dom` matchers to your Vite config:
19​
20**vite.config.ts**
21​
22```ts
23import { svelte } from '@sveltejs/vite-plugin-svelte'
24import { svelteTesting } from '@testing-library/svelte/vite'
25import { defineConfig } from 'vitest/config'
26​
27export default defineConfig({
28 plugins: [svelte(), svelteTesting()],
29 test: {
30 environment: 'jsdom',
31 setupFiles: ['./vitest-setup.ts'],
32 },
33})
34```
35​
36**vitest-setup.ts**
37​
38```ts
39import '@testing-library/jest-dom/vitest'
40```
41​
42In a SvelteKit project, use the `sveltekit()` plugin from `@sveltejs/kit/vite` instead of `svelte()`.
43​
44## Our First Test
45​
46Given the following query options, shared with [`queryOptions`](./reference/functions/queryOptions.md):
47​
48**queries.ts**
49​
50```ts
51import { queryOptions } from '@tanstack/svelte-query'
52​
53export const greetingOptions = queryOptions({
54 queryKey: ['greeting'],
55 queryFn: () =>
56 new Promise<string>((resolve) => setTimeout(() => resolve('Hello'), 10)),
57})
58```
59​
60There is no Svelte context outside of a component, so pass a fresh `QueryClient` to `createQuery` as its second argument. Create the query inside `$effect.root`, wait until it succeeds, and clean up the effect root in `finally`, so it is cleaned up even when an assertion fails:
61​
62**queries.svelte.test.ts**
63​
64```ts
65import { QueryClient, createQuery } from '@tanstack/svelte-query'
66import { expect, it, vi } from 'vitest'
67import { greetingOptions } from './queries'
68import type { CreateQueryResult } from '@tanstack/svelte-query'
69​
70it('should fetch the greeting', async () => {
71 const queryClient = new QueryClient()
72 let query!: CreateQueryResult<string>
73 const cleanup = $effect.root(() => {
74 query = createQuery(
75 () => greetingOptions,
76 () => queryClient,
77 )
78 })
79​
80 try {
81 await vi.waitFor(() => expect(query.isSuccess).toBe(true))
82​
83 expect(query.data).toBe('Hello')
84 } finally {
85 cleanup()
86 }
87})
88```
89​
90To avoid repeating `$effect.root` and its cleanup in every test, you can also wrap the whole test body with a helper that runs it inside an effect root:
91​
92```ts
93import { QueryClient, createQuery } from '@tanstack/svelte-query'
94import { expect, it, vi } from 'vitest'
95import { greetingOptions } from './queries'
96​
97function withEffectRoot(fn: () => Promise<void>) {
98 return async () => {
99 let promise!: Promise<void>
100 const cleanup = $effect.root(() => {
101 promise = fn()
102 })
103 try {
104 await promise
105 } finally {
106 cleanup()
107 }
108 }
110​
111it(
112 'should fetch the greeting',
113 withEffectRoot(async () => {
114 const queryClient = new QueryClient()
115 const query = createQuery(
116 () => greetingOptions,
117 () => queryClient,
118 )
119​
120 await vi.waitFor(() => expect(query.isSuccess).toBe(true))
121​
122 expect(query.data).toBe('Hello')
123 }),
125```
126​
127Note that we create a new `QueryClient` for every test. This helps to ensure that our test is completely isolated from any other tests.
128​
129It is possible to share a single `QueryClient` between tests, but if so we need to ensure that the `QueryClient` gets cleared before every test, and that tests don't run in parallel otherwise one test will influence the results of others.
130​
131`query` is reactive, so read its properties after waiting instead of destructuring them up front. A destructured value keeps the value it had when it was read.
132​
133## Testing components
134​
135Components read the `QueryClient` from the context that `QueryClientProvider` sets. Given a component that uses the same query options:
136​
137**Greeting.svelte**
138​
139```svelte
140<script lang="ts">
141 import { createQuery } from '@tanstack/svelte-query'
142 import { greetingOptions } from './queries'
143​
144 const query = createQuery(() => greetingOptions)
145</script>
146​
147{#if query.isPending}
148 <p>Loading...</p>
149{:else if query.isError}
150 <p>Error: {query.error.message}</p>
151{:else}
152 <p>{query.data}</p>
153{/if}
154```
155​
156Wrap it in `QueryClientProvider` in a component that only exists for the test:
157​
158**GreetingTest.svelte**
159​
160```svelte
161<script lang="ts">
162 import { QueryClientProvider } from '@tanstack/svelte-query'
163 import type { QueryClient } from '@tanstack/svelte-query'
164 import Greeting from './Greeting.svelte'
165​
166 let { queryClient }: { queryClient: QueryClient } = $props()
167</script>
168​
169<QueryClientProvider client={queryClient}>
170 <Greeting />
171</QueryClientProvider>
172```
173​
174Then render it with a fresh `QueryClient` and wait for the data to be rendered:
175​
176**Greeting.svelte.test.ts**
177​
178```ts
179import { QueryClient } from '@tanstack/svelte-query'
180import { render } from '@testing-library/svelte'
181import { expect, it } from 'vitest'
182import GreetingTest from './GreetingTest.svelte'
183​
184it('should render the greeting', async () => {
185 const rendered = render(GreetingTest, {
186 props: { queryClient: new QueryClient() },
187 })
188​
189 expect(rendered.getByText('Loading...')).toBeInTheDocument()
190 expect(await rendered.findByText('Hello')).toBeInTheDocument()
191})
192```
193​
194## Fake timers
195​
196`vi.waitFor` and `findByText` retry until the assertion passes, which works for query functions that wait on real requests. When the query function waits on a timer, you can use fake timers and advance them instead, for example with [`vi.advanceTimersByTimeAsync`](https://vitest.dev/api/vi.html#vi-advancetimersbytimeasync). Restore real timers in `afterEach`, so they are restored even when an assertion fails:
197​
198```ts
199import { QueryClient } from '@tanstack/svelte-query'
200import { render } from '@testing-library/svelte'
201import { afterEach, beforeEach, expect, it, vi } from 'vitest'
202import GreetingTest from './GreetingTest.svelte'
203​
204beforeEach(() => {
205 vi.useFakeTimers()
206})
207​
208afterEach(() => {
209 vi.useRealTimers()
210})
211​
212it('should render the greeting', async () => {
213 const rendered = render(GreetingTest, {
214 props: { queryClient: new QueryClient() },
215 })
216​
217 expect(rendered.getByText('Loading...')).toBeInTheDocument()
218​
219 await vi.advanceTimersByTimeAsync(10)
220​
221 expect(rendered.getByText('Hello')).toBeInTheDocument()
222})
223```
224​
225## Turn off retries
226​
227The library defaults to three retries with exponential backoff, which means that your tests are likely to timeout if you want to test an erroneous query. The easiest way to turn retries off is via the `QueryClient` that you use in the test:
228​
229```ts
230const queryClient = new QueryClient({
231 defaultOptions: {
232 queries: {
233 // βœ… turns retries off
234 retry: false,
235 },
236 },
237})
238```
239​
240This will set the defaults for all queries that use this client to "no retries". It is important to know that this will only work if your actual `createQuery` has no explicit retries set. If you have a query that wants 5 retries, this will still take precedence, because defaults are only taken as a fallback.