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

testing.md

161 lines5.6 KB

1---
2id: testing
3title: Testing
4---
5​
6Vue Query works by means of composables - either the ones we offer or custom ones that wrap around them.
7​
8These composables need the `QueryClient` that `VueQueryPlugin` provides, so they have to run inside the `setup` of a component that has the plugin installed. Writing unit tests for them can be done by means of [Vue Test Utils](https://test-utils.vuejs.org/).
9​
10## Setup
11​
12Following the [Testing Composables](https://vuejs.org/guide/scaling-up/testing.html#testing-composables) approach of the Vue docs, we write a `withSetup` helper that mounts a component, runs the composable in its `setup` and installs `VueQueryPlugin` with a `QueryClient`. The helper differs between Vue 3 and Vue 2, because they use different major versions of Vue Test Utils.
13​
14### Vue 3
15​
16Install Vue Test Utils 2 by running:
17​
18```sh
19npm install @vue/test-utils --save-dev
20```
21​
22```ts
23import { defineComponent } from 'vue'
24import { flushPromises, mount } from '@vue/test-utils'
25import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
26​
27function withSetup<T>(composable: () => T, queryClient = new QueryClient()) {
28 let result!: T
29 const wrapper = mount(
30 defineComponent({
31 setup() {
32 result = composable()
33 return () => null
34 },
35 }),
36 { global: { plugins: [[VueQueryPlugin, { queryClient }]] } },
37 )
38 return [result, wrapper] as const
40```
41​
42### Vue 2
43​
44Vue Test Utils 1 does not export `flushPromises`, so install the `flush-promises` package along with it:
45​
46```sh
47npm install @vue/test-utils@1 flush-promises --save-dev
48```
49​
50```ts
51import { defineComponent } from 'vue'
52import { createLocalVue, mount } from '@vue/test-utils'
53import flushPromises from 'flush-promises'
54import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
55​
56function withSetup<T>(composable: () => T, queryClient = new QueryClient()) {
57 let result!: T
58 const localVue = createLocalVue()
59 localVue.use(VueQueryPlugin, { queryClient })
60 const wrapper = mount(
61 defineComponent({
62 setup() {
63 result = composable()
64 return () => null
65 },
66 }),
67 { localVue },
68 )
69 return [result, wrapper] as const
71```
72​
73With Vue 2.6, also call `localVue.use(VueCompositionApi)` before installing `VueQueryPlugin`, and import `VueCompositionApi` and `defineComponent` from `@vue/composition-api`.
74​
75## Our First Test
76​
77Once set up, a simple test can be written. Given the following custom composable:
78​
79```ts
80export function useCustomComposable() {
81 return useQuery({ queryKey: ['customComposable'], queryFn: () => 'Hello' })
83```
84​
85We can write a test for this as follows:
86​
87```ts
88const [result, wrapper] = withSetup(() => useCustomComposable())
89​
90await flushPromises()
91​
92expect(result.isSuccess.value).toBe(true)
93expect(result.data.value).toEqual('Hello')
94​
95wrapper.unmount()
96```
97​
98With Vue Test Utils 1, call `wrapper.destroy()` instead of `wrapper.unmount()`.
99​
100Note that `withSetup` creates a new `QueryClient` for every call. This helps to ensure that our test is completely isolated from any other tests. Unmounting the wrapper at the end of the test removes the query observers that the composable created.
101​
102It 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.
103​
104`flushPromises` is enough here because the query function resolves right away. When the query function waits on a timer, use fake timers and advance them, 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:
105​
106```ts
107beforeEach(() => {
108 vi.useFakeTimers()
109})
110​
111afterEach(() => {
112 vi.useRealTimers()
113})
114​
115it('should resolve the delayed query', async () => {
116 const [result, wrapper] = withSetup(() =>
117 useQuery({
118 queryKey: ['delayed'],
119 queryFn: () =>
120 new Promise((resolve) => setTimeout(() => resolve('Hello'), 1000)),
121 }),
122 )
123​
124 await vi.advanceTimersByTimeAsync(1000)
125​
126 expect(result.data.value).toEqual('Hello')
127​
128 wrapper.unmount()
129})
130```
131​
132When the query function waits on a real request, wait until the assertion passes instead, for example with [`vi.waitFor`](https://vitest.dev/api/vi.html#vi-waitfor):
133​
134```ts
135await vi.waitFor(() => expect(result.isSuccess.value).toBe(true))
136```
137​
138For more complex composables, it can be easier to test the component that uses them instead, by mounting it with the same plugin setup and asserting on what it renders.
139​
140## Turn off retries
141​
142The 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 `VueQueryPlugin`. Let's extend the above example:
143​
144```ts
145const queryClient = new QueryClient({
146 defaultOptions: {
147 queries: {
148 // βœ… turns retries off
149 retry: false,
150 },
151 },
152})
153​
154const [result, wrapper] = withSetup(() => useCustomComposable(), queryClient)
155```
156​
157This will set the defaults for all queries in the app 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.
158​
159## Set gcTime to Infinity with Jest
160​
161If 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`.