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

testing.md

208 lines6.7 KB

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 { LitElement, html } from 'lit'
62import { createQueryController } from '@tanstack/lit-query'
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 }
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 { afterEach, expect, it, vi } from 'vitest'
87import { QueryClient } from '@tanstack/lit-query'
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 { afterEach, expect, it, vi } from 'vitest'
124import { LitElement } from 'lit'
125import { QueryClient, createQueryController } from '@tanstack/lit-query'
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 { afterEach, beforeEach, expect, it, vi } from 'vitest'
161import { QueryClient } from '@tanstack/lit-query'
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.