| | |

Vue Query 14 ⚡ Testing Vue Query — Setting up isolated QueryClient instances and testing components/composables in Vitest

⏱️ Estimated read: 11 min | |

Testing applications that rely on complex asynchronous state management can be challenging. Because Vue Query maintains a global cache of data, tests can easily become “polluted” if state from one test case leaks into another. For example, if a test successfully fetches a list of users and the next test case is supposed to verify an empty state, the second test might fail because it finds the “stale” data still sitting in the cache. To prevent this, developers must implement a strategy of strict isolation, ensuring that every individual test run starts with a completely fresh, empty QueryClient instance.

Furthermore, testing asynchronous components requires a different mental model than testing static UI. We must account for the “Loading -> Success” or “Loading -> Error” transitions. This involves using tools like Vitest and Vue Test Utils to mount components, wait for the internal promises of Vue Query to resolve, and assert against the resulting DOM changes. Mocking the network layer—typically through MSW (Mock Service Worker) or simple Vitest spies—is essential to keep tests fast, deterministic, and independent of external API availability.

This chapter covers the technical setup for testing Vue Query within a Vitest environment. We will explore the creation of factory functions for QueryClient instances, the proper way to inject the VueQueryPlugin into component tests, and methodologies for testing custom composables that wrap useQuery or useMutation. By mastering these patterns, you can ensure your data-fetching logic is resilient and that your test suite remains reliable as your application grows in complexity.

Key point: Testing Vue Query requires creating a fresh QueryClient for every test to prevent cache pollution and disabling default retries to ensure that failure scenarios report errors immediately in the test runner.


Why exists

The State Pollution problem. Vue Query is designed to share data across components using a centralized cache. In a testing suite, this “feature” becomes a bug. If Test A populates the cache and Test B assumes it is empty, Test B will provide false results. Isolation via fresh instances is the only cure.

The Asynchronous Timing problem. Asynchronous data fetching doesn’t happen instantly. Tests often try to assert on data that hasn’t arrived yet. Testing patterns for Vue Query provide standardized ways to “await” the resolution of queries before running assertions.

The Retry Latency problem. By default, Vue Query retries failed requests three times with exponential backoff. In a test environment, waiting for three retries to fail can turn a 2-second test suite into a 30-second one. Configuring specific test-defaults (like retry: false) is essential for speed.

The Mocking consistency problem. Directly mocking useQuery return values is brittle because it bypasses the internal cache logic. It is better to mock the network layer and let the real Vue Query logic run, ensuring that your tests reflect how the library actually behaves in production.

The Composable Logic gap. Many developers wrap Vue Query in custom composables (e.g., useUser()). Testing these in isolation—without a component—requires a “Wrapper” component pattern to provide the necessary injection context that Vue Query expects.

The Server-Side Rendering (SSR) parity. Testing ensures that the dehydration and hydration logic works as expected. By simulating SSR environments in Vitest, you can verify that data fetched on the “server” is correctly picked up by the “client” without triggering a double-fetch.


a. Isolated QueryClient Configuration

The most important step in testing Vue Query is creating a factory function that generates a new QueryClient for every test. This ensures that every test starts with an empty cache. Additionally, we typically disable retries in the testing configuration. In a real app, retries are great; in a test, if a request is mocked to fail, we want it to fail immediately so we can assert on the error state.

// tests/utils.ts
import { QueryClient } from '@tanstack/vue-query'

export const createTestQueryClient = () => {
  return new QueryClient({
    defaultOptions: {
      queries: {
        // Disabling retries prevents Vitest from hanging 
        // while waiting for backoff timers
        retry: false,
        // Prevents data from becoming "stale" immediately during a test
        staleTime: Infinity,
      },
    },
  })
}

In your Vitest setup, you can use this factory in a beforeEach block. However, it is usually cleaner to create the client inside the mount call of each individual test to keep dependencies explicit.

import { beforeEach, vi } from 'vitest'
import { createTestQueryClient } from './utils'

// Clear all mocks and caches before each test
beforeEach(() => {
  vi.clearAllMocks()
})

b. Testing Components with Vue Test Utils

When testing a component that uses useQuery, you must provide the QueryClient instance via the VueQueryPlugin. If you fail to do this, the component will throw an error because it cannot find the injected client. We use the global.plugins option in Vue Test Utils to register the plugin and pass our isolated client.

// UserProfile.test.ts
import { mount } from '@vue/test-utils'
import { VueQueryPlugin } from '@tanstack/vue-query'
import UserProfile from './UserProfile.vue'
import { createTestQueryClient } from './utils'

test('renders loading state then data', async () => {
  const queryClient = createTestQueryClient()

  const wrapper = mount(UserProfile, {
    global: {
      plugins: [[VueQueryPlugin, { queryClient }]],
    },
  })

  // Assert initial loading state
  expect(wrapper.text()).toContain('Loading...')

  // Wait for the query to resolve (using a helper or simple timeout)
  // flushPromises is often used to wait for all pending async operations
  await flushPromises()

  expect(wrapper.text()).toContain('John Doe')
})

It is highly recommended to use a library like msw (Mock Service Worker) to handle the network layer. MSW intercepts actual fetch calls, allowing Vue Query to go through its full lifecycle (Pending -> Success) as if it were talking to a real server, but with deterministic data.


c. Testing Custom Composables

Testing a composable that uses useQuery (like useUser(id)) is slightly more complex because composables must be executed within the context of a Vue app to access provide/inject. The standard pattern is to create a “Test Wrapper” component that executes the composable and exposes its result.

// useUser.test.ts
import { defineComponent, h } from 'vue'
import { mount } from '@vue/test-utils'
import { useUser } from './useUser'
import { createTestQueryClient } from './utils'
import { VueQueryPlugin } from '@tanstack/vue-query'

const mountComposable = (setup: () => any) => {
  let result: any
  const TestComponent = defineComponent({
    setup() {
      result = setup()
      return () => h('div')
    },
  })

  mount(TestComponent, {
    global: {
      plugins: [[VueQueryPlugin, { queryClient: createTestQueryClient() }]],
    },
  })

  return result
}

test('composable fetches user', async () => {
  const { data, isSuccess } = mountComposable(() => useUser('123'))

  await waitUntil(() => isSuccess.value)

  expect(data.value.name).toBe('John Doe')
})

By wrapping the composable in a component, we ensure that Vue Query’s internal useQueryClient() hook finds the client we injected via the plugin. This “Wrapper” pattern is the most reliable way to test headless logic that relies on Vue’s dependency injection system.


Complete Example Session

// ============================================
// PART 1: THE COMPOSABLE TO TEST
// ============================================
export const usePosts = () => useQuery({
  queryKey: ['posts'],
  queryFn: () => fetch('/api/posts').then(res => res.json())
})

// ============================================
// PART 2: THE COMPONENT TO TEST
// ============================================
/* 
// Posts.vue
<template>
  <div v-if="isPending">Loading...</div>
  <ul v-else><li v-for="p in data">{{ p.title }}</li></ul>
</template>
*/

// ============================================
// PART 3: TEST UTILITY - CLIENT FACTORY
// ============================================
import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
const createClient = () => new QueryClient({
  defaultOptions: { queries: { retry: false } }
})

// ============================================
// PART 4: MOCKING THE API (Simple Fetch Mock)
// ============================================
const mockFetch = (data: any) => {
  global.fetch = vi.fn().mockResolvedValue({
    json: () => Promise.resolve(data),
    ok: true
  })
}

// ============================================
// PART 5: COMPONENT TEST - SUCCESS
// ============================================
it('shows posts on success', async () => {
  mockFetch([{ title: 'Hello World' }])
  const wrapper = mount(Posts, {
    global: { plugins: [[VueQueryPlugin, { queryClient: createClient() }]] }
  })
  await flushPromises()
  expect(wrapper.text()).toContain('Hello World')
})

// ============================================
// PART 6: COMPONENT TEST - LOADING
// ============================================
it('shows spinner while loading', () => {
  mockFetch(new Promise(() => {})) // Never resolves
  const wrapper = mount(Posts, {
    global: { plugins: [[VueQueryPlugin, { queryClient: createClient() }]] }
  })
  expect(wrapper.text()).toContain('Loading...')
})

// ============================================
// PART 7: COMPONENT TEST - ERROR
// ============================================
it('shows error message', async () => {
  global.fetch = vi.fn().mockRejectedValue(new Error('Failed'))
  const wrapper = mount(Posts, {
    global: { plugins: [[VueQueryPlugin, { queryClient: createClient() }]] }
  })
  await flushPromises()
  // ... check for error UI
})

// ============================================
// PART 8: TESTING MUTATION SIDE EFFECTS
// ============================================
// Trigger button -> check if queryClient.invalidateQueries was called

// ============================================
// PART 9: TESTING STALE DATA
// ============================================
// Mount -> Resolve -> Update Mock -> Invalidate -> Check for new data

// ============================================
// PART 10: CLEANUP
// ============================================
afterEach(() => { vi.restoreAllMocks() })

The sequence above builds a complete testing environment, starting from the logic under test to the infrastructure required to simulate various network and state conditions.


Quick Reference

Essential Testing Config

OptionRecommended ValuePurpose
retryfalseStop tests from hanging on failure
gcTime0 (or low)Cleanup memory quickly between tests
staleTimeInfinityPrevent unexpected background refetches during assertions

Vue Test Utils Helpers

HelperPurpose
global.pluginsWhere to inject the VueQueryPlugin
flushPromises()Wait for all pending promises (including fetch and cache)
mount()Renders the component into the test DOM

Mocking Network

LibraryStrategy
MSWService worker interception (Most Realistic)
Vitest Spiesvi.spyOn(global, 'fetch') (Fastest/Simplest)
Axios Mock AdapterDedicated for Axios-based apps

Best Practices

✅ Do This:

// Create a new QueryClient for EVERY individual test
const client = createTestQueryClient();                        // ✅

// Use MSW to mock API responses globally
server.use(rest.get('/api/data', ...));                        // ✅

// Disable retries in tests to fail-fast
retry: false                                                   // ✅

// Use flushPromises() to wait for data to settle
await flushPromises();                                         // ✅

❌ Don’t Do This:

// Don't share one QueryClient instance across multiple test files
const globalClient = new QueryClient(); // State Leakage        // ❌

// Don't use real API endpoints in Vitest
// (Slows down CI and makes tests flaky)                       // ❌

// Don't manually mock useQuery's return object
vi.mock('...', () => ({ useQuery: () => ({ data: ... }) }));  // ❌
// (Bypasses the library's internal logic)

// Don't forget to wait for the next tick/promise
expect(wrapper.text()).toBe('Data'); // Before await...        // ❌

Common Pitfalls

PitfallWhy It HappensFix
Data leaks between testsUsing a singleton QueryClientInstantiate new QueryClient() in beforeEach
Test times outVue Query is retrying a failed fetch 3 timesSet retry: false in defaultOptions
UI shows loading foreverPromise in mockFetch never resolvedEnsure mock fetch resolves with data or error
“No QueryClient found”VueQueryPlugin missing from global.pluginsAdd plugin to mount() options
Component state doesn’t updateawait flushPromises() was forgottenAlways wait for promises after an async action

Real-World Examples

1. Setup MSW Server

const server = setupServer(...handlers);
beforeAll(() => server.listen());

2. Isolated Client Factory

const createClient = () => new QueryClient({ defaultOptions: { queries: { retry: false }}});

3. Injecting Plugin in Test

mount(Comp, { global: { plugins: [[VueQueryPlugin, { queryClient }]] } });

4. Waiting for Mutation

await wrapper.find('form').trigger('submit');
await flushPromises();

5. Testing Error Boundaries

server.use(rest.get('/api', (req, res, ctx) => res(ctx.status(500))));

6. Mocking Suspense

const wrapper = mount(SuspenseWrapper, { props: { component: MyAsyncComp }});

7. Testing Cache Persistence

client.setQueryData(['key'], 'old-data');
// Verify if component displays 'old-data' initially

8. Manual Invalidation Test

const spy = vi.spyOn(queryClient, 'invalidateQueries');
await wrapper.find('button').trigger('click');
expect(spy).toHaveBeenCalledWith({ queryKey: ['users'] });

9. Testing Loading Skeleton

expect(wrapper.findComponent(Skeleton).exists()).toBe(true);

10. Custom Hook Wrapper

const result = mountComposable(() => useMyHook());

Visual

Cache Pollution (The Problem)

┌──────────────────────────────────────────────────────────┐
│ TEST A: Fetch User 1                                     │
│  - QueryClient Cache: { 'user-1': { name: 'Alice' } }    │
└──────────────────────────┬───────────────────────────────┘
                           │ (Pollution)
                           ▼
┌──────────────────────────────────────────────────────────┐
│ TEST B: Check Empty State                                │
│  - ERROR: Test B finds Alice in the cache!               │
└──────────────────────────────────────────────────────────┘

Isolated Clients (The Solution)

┌──────────────────────────────────────────────────────────┐
│ TEST A                                                   │
│  - Client A Instance ──► [ Fresh Cache ]                 │
└──────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────┐
│ TEST B                                                   │
│  - Client B Instance ──► [ Fresh Cache ]                 │
└──────────────────────────────────────────────────────────┘

Testing Lifecycle

1. SETUP   ──► Mock Network (MSW) & Create isolated QueryClient
2. ACTION  ──► Mount Component with VueQueryPlugin
3. WAIT    ──► await flushPromises() (Data arrives)
4. ASSERT  ──► expect(UI).toContain(Data)
5. CLEANUP ──► Reset Mocks & Clear Client

Composable Injection Context

┌──────────────────────────────────────────────────────────┐
│ Test Wrapper Component                                   │
│  ┌────────────────────────────────────────────────────┐  │
│  │ setup() {                                          │  │
│  │   const data = useMyComposable(); // Injected Context! │
│  │   return { data };                                 │  │
│  │ }                                                  │  │
│  └────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Target RunnerVitest
Provider PluginVueQueryPlugin
Key Configretry: false
Sync ToolflushPromises()
Context PatternWrapper Component
Mocking LayerMSW or Spies
Cache StateMust be reset per test

Key takeaways:

  • Isolation is the priority. Always instantiate a new QueryClient for every test to prevent cache data from leaking and causing flaky tests .
  • Disable retries for speed. Tests should fail immediately when an error is expected. Default retries add unnecessary latency to your test suite .
  • Mock the network, not the library. Use MSW to intercept fetch calls. This allows you to test your application as a whole while keeping Vue Query’s logic intact .
  • Use flushPromises for async settling. Component templates won’t update until all pending microtasks (like fetch resolution and cache updates) are finished .
  • Wrap composables for context. Custom hooks that use useQuery need a Vue instance to provide the QueryClient. A simple “TestComponent” is the standard way to provide this context .
  • Verification of cache side effects. Testing is not just about the UI; you should also assert that actions like invalidateQueries were called correctly when mutations occur .

Remember: A reliable test suite for Vue Query relies on a clean slate for every test run. By isolating your QueryClient and mocking the network layer correctly, you ensure that your tests are deterministic, fast, and representative of real-world application behavior.

_

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!