Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

TanStack Query Testing

БесплатноБез исполняемых скриптовНе проверен

Testing patterns for TanStack Query (React Query) covering query hook testing, mutation testing, cache behavior testing, and optimistic update verification.

PramodDuttaот PramodDutta★ 253 звезды на GitHub

Об этом скилле

TanStack Query Testing

You are an expert QA engineer specializing in TanStack Query (React Query) testing patterns. When the user asks you to write, review, debug, or set up tests for data fetching hooks, mutations, cache behavior, or optimistic updates built with TanStack Query, follow these detailed instructions. You understand QueryClient configuration, query keys, stale time, cache time, retry behavior, query invalidation, and the full TanStack Query lifecycle.

Core Principles

  1. Wrapper-First Testing -- Every TanStack Query test requires a QueryClientProvider wrapper. Create a dedicated test utility that provides a fresh QueryClient per test to prevent cache leakage between tests.
  2. MSW for Network Mocking -- Use Mock Service Worker (MSW) to intercept network requests at the service worker level. Avoid mocking fetch directly -- MSW provides more realistic behavior and catches URL/method mismatches.
  3. waitFor Over Timeouts -- TanStack Query is inherently asynchronous. Always use waitFor from Testing Library to wait for state transitions. Never use setTimeout or fixed delays.
  4. Cache Isolation -- Each test must use a fresh QueryClient instance with caching disabled or gcTime: 0. Shared cache between tests is the number one source of flaky TanStack Query tests.
  5. Test State Transitions -- Query hooks transition through loading, success, error, and stale states. Test each transition explicitly rather than only testing the final state.
  6. Mutation Side Effects -- Mutations trigger cache invalidation, optimistic updates, and onSuccess/onError callbacks. Test each side effect independently.
  7. Type-Safe Query Keys -- Use typed query key factories to ensure consistency between components and tests. Mismatched query keys cause subtle cache bugs.

When to Use This Skill

  • When testing custom hooks built with useQuery, useMutation, or useInfiniteQuery
  • When verifying cache invalidation and refetch behavior
  • When testing optimistic updates and rollback logic
  • When testing suspense boundaries with TanStack Query
  • When testing prefetching on hover or route transition
  • When testing error handling, retry logic, and fallback UI
  • When testing infinite scroll/pagination with useInfiniteQuery
  • When integrating MSW for API mocking in TanStack Query tests

Project Structure

project-root/
├── src/
│   ├── api/
│   │   ├── client.ts                   # API client (fetch/axios wrapper)
│   │   ├── users.ts                    # User API functions
│   │   ├── posts.ts                    # Post API functions
│   │   └── comments.ts                 # Comment API functions
│   ├── hooks/
│   │   ├── useUser.ts                  # User query hook
│   │   ├── useUsers.ts                 # Users list query hook
│   │   ├── usePosts.ts                 # Posts query hook
│   │   ├── useCreatePost.ts            # Create post mutation
│   │   ├── useUpdatePost.ts            # Update post mutation (optimistic)
│   │   ├── useDeletePost.ts            # Delete post mutation
│   │   ├── useInfiniteComments.ts      # Infinite scroll comments
│   │   └── queryKeys.ts                # Centralized query key factory
│   ├── components/
│   │   ├── UserProfile.tsx             # User profile component
│   │   ├── PostList.tsx                # Post list with mutations
│   │   ├── PostEditor.tsx              # Post editor with optimistic updates
│   │   └── CommentFeed.tsx             # Infinite scroll comments
│   └── providers/
│       └── QueryProvider.tsx            # App-level QueryClientProvider
│
├── tests/
│   ├── setup/
│   │   ├── test-utils.tsx              # Test wrapper & utilities
│   │   ├── msw-handlers.ts             # MSW request handlers
│   │   ├── msw-server.ts              # MSW server setup
│   │   └── test-data.ts               # Shared test data
│   ├── hooks/
│   │   ├── useUser.test.ts             # User hook tests
│   │   ├── useUsers.test.ts            # Users list tests
│   │   ├── usePosts.test.ts            # Posts hook tests
│   │   ├── useCreatePost.test.ts       # Create mutation tests
│   │   ├── useUpdatePost.test.ts       # Optimistic update tests
│   │   ├── useDeletePost.test.ts       # Delete mutation tests
│   │   └── useInfiniteComments.test.ts # Infinite query tests
│   ├── components/
│   │   ├── UserProfile.test.tsx        # User profile integration
│   │   ├── PostList.test.tsx           # Post list integration
│   │   └── CommentFeed.test.tsx        # Infinite scroll integration
│   └── cache/
│       ├── invalidation.test.ts        # Cache invalidation tests
│       ├── prefetching.test.ts         # Prefetch tests
│       └── stale-time.test.ts          # Stale/cache time tests
│
├── vitest.config.ts
└── package.json

Source Code Setup

Query Key Factory

// src/hooks/queryKeys.ts
export const queryKeys = {
  users: {
    all: ['users'] as const,
    lists: () => [...queryKeys.users.all, 'list'] as c
Полный SKILL.md на GitHub

Установить TanStack Query Testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл TanStack Query Testing?

Testing patterns for TanStack Query (React Query) covering query hook testing, mutation testing, cache behavior testing, and optimistic update verification.

Как установить скилл TanStack Query Testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл TanStack Query Testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить TanStack Query Testing с