Open History to see the last commit
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 }
109}
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 }),
124)
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.