Open History to see the last commit
1---
2id: testing
3title: Testing
4---
5β
6Lit Query works by means of reactive controllers like `createQueryController`, attached to a host element. A controller reads the `QueryClient` from the nearest connected `QueryClientProvider`, or from the `QueryClient` you pass as its last argument, and subscribes when its host connects to the document.
7β
8So, to test a query, connect its host element to the document, wait for the element to update, and assert on what it renders or on the controller's result.
9β
10## Setup
11β
12This guide uses [Vitest](https://vitest.dev/) with jsdom, like Lit Query's own tests, and the [`jest-dom`](https://github.com/testing-library/jest-dom) matchers. Install them by running:
13β
14```sh
15npm install vitest jsdom @testing-library/jest-dom --save-dev
16```
17β
18Then use jsdom and add a setup file that loads the matchers and registers `QueryClientProvider` once:
19β
20**vite.config.ts**
21β
22```ts
23import { defineConfig } from 'vitest/config'
24β
25export default defineConfig({
26 test: {
27 environment: 'jsdom',
28 setupFiles: ['./vitest-setup.ts'],
29 },
30})
31```
32β
33**vitest-setup.ts**
34β
35```ts
36import '@testing-library/jest-dom/vitest'
37import { QueryClientProvider } from '@tanstack/lit-query'
38β
39customElements.define('query-client-provider', QueryClientProvider)
40```
41β
42## Our First Test
43β
44Given the following query options, shared with [`queryOptions`](../reference/functions/queryOptions.md), and an element that uses them:
45β
46**queries.ts**
47β
48```ts
49import { queryOptions } from '@tanstack/lit-query'
50β
51export const greetingOptions = queryOptions({
52 queryKey: ['greeting'],
53 queryFn: () =>
54 new Promise<string>((resolve) => setTimeout(() => resolve('Hello'), 10)),
55})
56```
57β
58**greeting-view.ts**
59β
60```ts
61import { createQueryController } from '@tanstack/lit-query'
62import { LitElement, html } from 'lit'
63import { greetingOptions } from './queries'
64β
65export class GreetingView extends LitElement {
66 private readonly greeting = createQueryController(this, greetingOptions)
67β
68 render() {
69 const query = this.greeting()
70β
71 if (query.isPending) return html`<p>Loading...</p>`
72 if (query.isError) return html`<p>Error: ${query.error.message}</p>`
73β
74 return html`<p>${query.data}</p>`
75 }
76}
77β
78customElements.define('greeting-view', GreetingView)
79```
80β
81We can render the element under a `QueryClientProvider` with a fresh `QueryClient`, wait for its first update, and then wait until the data is rendered:
82β
83**greeting-view.test.ts**
84β
85```ts
86import { QueryClient } from '@tanstack/lit-query'
87import { afterEach, expect, it, vi } from 'vitest'
88import type { QueryClientProvider } from '@tanstack/lit-query'
89import type { GreetingView } from './greeting-view'
90import './greeting-view'
91β
92afterEach(() => {
93 document.body.replaceChildren()
94})
95β
96it('should render the greeting', async () => {
97 const provider = document.createElement(
98 'query-client-provider',
99 ) as QueryClientProvider
100 provider.client = new QueryClient()
101 const view = document.createElement('greeting-view') as GreetingView
102 provider.append(view)
103 document.body.append(provider)
104β
105 await view.updateComplete
106 expect(view.shadowRoot).toHaveTextContent('Loading...')
107β
108 await vi.waitFor(() => expect(view.shadowRoot).toHaveTextContent('Hello'))
109})
110```
111β
112Removing the elements in `afterEach` disconnects them, so their controllers unsubscribe from the `QueryClient`.
113β
114Note that we create a new `QueryClient` for every test. This helps to ensure that our test is completely isolated from any other tests.
115β
116It 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.
117β
118## Testing a controller on its own
119β
120To test the query without rendering, attach the controller to a host element that only exists for the test, and pass the `QueryClient` as its last argument instead of rendering a provider. Then assert on the controller's result:
121β
122```ts
123import { QueryClient, createQueryController } from '@tanstack/lit-query'
124import { LitElement } from 'lit'
125import { afterEach, expect, it, vi } from 'vitest'
126import { greetingOptions } from './queries'
127β
128afterEach(() => {
129 document.body.replaceChildren()
130})
131β
132it('should fetch the greeting', async () => {
133 const queryClient = new QueryClient()
134β
135 class TestHost extends LitElement {
136 readonly greeting = createQueryController(
137 this,
138 greetingOptions,
139 queryClient,
140 )
141 }
142 customElements.define('test-host', TestHost)
143β
144 const host = new TestHost()
145 document.body.append(host)
146β
147 await vi.waitFor(() => expect(host.greeting().isSuccess).toBe(true))
148β
149 expect(host.greeting().data).toBe('Hello')
150})
151```
152β
153Custom element names can only be registered once, so give each test host its own name.
154β
155## Fake timers
156β
157`vi.waitFor` retries 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:
158β
159```ts
160import { QueryClient } from '@tanstack/lit-query'
161import { afterEach, beforeEach, expect, it, vi } from 'vitest'
162import type { QueryClientProvider } from '@tanstack/lit-query'
163import type { GreetingView } from './greeting-view'
164import './greeting-view'
165β
166beforeEach(() => {
167 vi.useFakeTimers()
168})
169β
170afterEach(() => {
171 document.body.replaceChildren()
172 vi.useRealTimers()
173})
174β
175it('should render the greeting', async () => {
176 const provider = document.createElement(
177 'query-client-provider',
178 ) as QueryClientProvider
179 provider.client = new QueryClient()
180 const view = document.createElement('greeting-view') as GreetingView
181 provider.append(view)
182 document.body.append(provider)
183β
184 await view.updateComplete
185 expect(view.shadowRoot).toHaveTextContent('Loading...')
186β
187 await vi.advanceTimersByTimeAsync(10)
188β
189 expect(view.shadowRoot).toHaveTextContent('Hello')
190})
191```
192β
193## Turn off retries
194β
195The 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:
196β
197```ts
198const queryClient = new QueryClient({
199 defaultOptions: {
200 queries: {
201 // β
turns retries off
202 retry: false,
203 },
204 },
205})
206```
207β
208This 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 `createQueryController` 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.