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

testing.md

107 lines4.1 KB

1---
2id: testing
3title: Testing
4---
5​
6Solid Query works by means of primitives - either the ones we offer or custom ones that wrap around them.
7​
8These primitives read the `QueryClient` from `QueryClientProvider`, so they have to run under it. Writing unit tests for them can be done by means of `renderHook` from [Solid Testing Library](https://github.com/solidjs/solid-testing-library).
9​
10Install this by running:
11​
12```sh
13npm install @solidjs/testing-library --save-dev
14```
15​
16## Our First Test
17​
18Once installed, a simple test can be written. Given the following custom primitive:
19​
20```tsx
21export function useCustomQuery() {
22 return useQuery(() => ({ queryKey: ['customQuery'], queryFn: () => 'Hello' }))
24```
25​
26We can write a test for this as follows:
27​
28```tsx
29import { renderHook, waitFor } from '@solidjs/testing-library'
30import { QueryClient, QueryClientProvider } from '@tanstack/solid-query'
31import type { ParentProps } from 'solid-js'
32​
33const queryClient = new QueryClient()
34const wrapper = (props: ParentProps) => (
35 <QueryClientProvider client={queryClient}>
36 {props.children}
37 </QueryClientProvider>
39​
40const { result } = renderHook(() => useCustomQuery(), { wrapper })
41​
42await waitFor(() => expect(result.isSuccess).toBe(true))
43​
44expect(result.data).toEqual('Hello')
45```
46​
47Note that we provide a custom wrapper that builds the `QueryClient` and `QueryClientProvider`. This helps to ensure that our test is completely isolated from any other tests.
48​
49It is possible to write this wrapper only once, 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.
50​
51`result` is the reactive object that `useQuery` returns, not a snapshot, so read its properties after waiting instead of destructuring them up front. A destructured value keeps the value it had when it was read.
52​
53`waitFor` retries the assertion until it 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) in Vitest. Restore real timers in `afterEach`, so they are restored even when an assertion fails:
54​
55```tsx
56beforeEach(() => {
57 vi.useFakeTimers()
58})
59​
60afterEach(() => {
61 vi.useRealTimers()
62})
63​
64it('should resolve the delayed query', async () => {
65 const { result } = renderHook(
66 () =>
67 useQuery(() => ({
68 queryKey: ['delayed'],
69 queryFn: () =>
70 new Promise((resolve) => setTimeout(() => resolve('Hello'), 1000)),
71 })),
72 { wrapper },
73 )
74​
75 await vi.advanceTimersByTimeAsync(1000)
76​
77 expect(result.data).toEqual('Hello')
78})
79```
80​
81For more complex primitives, it can be easier to test the component that uses them instead, by rendering it with `render` from Solid Testing Library under the same `QueryClientProvider` and asserting on what it renders.
82​
83## Turn off retries
84​
85The 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 pass to `QueryClientProvider`. Let's extend the above example:
86​
87```tsx
88const queryClient = new QueryClient({
89 defaultOptions: {
90 queries: {
91 // βœ… turns retries off
92 retry: false,
93 },
94 },
95})
96const wrapper = (props: ParentProps) => (
97 <QueryClientProvider client={queryClient}>
98 {props.children}
99 </QueryClientProvider>
101```
102​
103This will set the defaults for all queries in the component tree to "no retries". It is important to know that this will only work if your actual `useQuery` 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.
104​
105## Set gcTime to Infinity with Jest
106​
107If you use Jest, you can set the `gcTime` to `Infinity` to prevent "Jest did not exit one second after the test run completed" error message. This is the default behavior on the server, and is only necessary to set if you are explicitly setting a `gcTime`.