test-query.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  2. import { ReactNode } from 'react';
  3. import { vi } from 'vitest';
  4. /**
  5. * 创建测试用的QueryClient(带默认配置)
  6. */
  7. export function createTestQueryClient(options = {}) {
  8. return new QueryClient({
  9. defaultOptions: {
  10. queries: {
  11. retry: false,
  12. gcTime: 0,
  13. staleTime: 0,
  14. },
  15. mutations: {
  16. retry: false,
  17. },
  18. },
  19. ...options
  20. });
  21. }
  22. /**
  23. * QueryProvider包装组件
  24. */
  25. export function TestQueryProvider({
  26. children,
  27. client
  28. }: {
  29. children: ReactNode;
  30. client?: QueryClient
  31. }) {
  32. const queryClient = client || createTestQueryClient();
  33. return (
  34. <QueryClientProvider client={queryClient}>
  35. {children}
  36. </QueryClientProvider>
  37. );
  38. }
  39. /**
  40. * Mock查询Hook
  41. */
  42. export function mockUseQuery(data: any, isLoading = false, error: any = null) {
  43. return vi.fn().mockReturnValue({
  44. data,
  45. isLoading,
  46. isError: !!error,
  47. error,
  48. isSuccess: !isLoading && !error,
  49. refetch: vi.fn(),
  50. });
  51. }
  52. /**
  53. * Mock变更Hook
  54. */
  55. export function mockUseMutation() {
  56. return vi.fn().mockReturnValue({
  57. mutate: vi.fn(),
  58. mutateAsync: vi.fn().mockResolvedValue({}),
  59. isLoading: false,
  60. isError: false,
  61. error: null,
  62. isSuccess: false,
  63. reset: vi.fn(),
  64. });
  65. }
  66. /**
  67. * 等待查询完成
  68. */
  69. export async function waitForQueryToFinish(delay = 100) {
  70. await new Promise(resolve => setTimeout(resolve, delay));
  71. }
  72. /**
  73. * 模拟网络错误
  74. */
  75. export function mockNetworkError() {
  76. return new Error('Network error');
  77. }
  78. /**
  79. * 模拟服务器错误
  80. */
  81. export function mockServerError() {
  82. return new Error('Server error');
  83. }