test-query.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. {/* @ts-ignore */}
  36. {children}
  37. </QueryClientProvider>
  38. );
  39. }
  40. /**
  41. * Mock查询Hook
  42. */
  43. export function mockUseQuery(data: any, isLoading = false, error: any = null) {
  44. return vi.fn().mockReturnValue({
  45. data,
  46. isLoading,
  47. isError: !!error,
  48. error,
  49. isSuccess: !isLoading && !error,
  50. refetch: vi.fn(),
  51. });
  52. }
  53. /**
  54. * Mock变更Hook
  55. */
  56. export function mockUseMutation() {
  57. return vi.fn().mockReturnValue({
  58. mutate: vi.fn(),
  59. mutateAsync: vi.fn().mockResolvedValue({}),
  60. isLoading: false,
  61. isError: false,
  62. error: null,
  63. isSuccess: false,
  64. reset: vi.fn(),
  65. });
  66. }
  67. /**
  68. * 等待查询完成
  69. */
  70. export async function waitForQueryToFinish(delay = 100) {
  71. await new Promise(resolve => setTimeout(resolve, delay));
  72. }
  73. /**
  74. * 模拟网络错误
  75. */
  76. export function mockNetworkError() {
  77. return new Error('Network error');
  78. }
  79. /**
  80. * 模拟服务器错误
  81. */
  82. export function mockServerError() {
  83. return new Error('Server error');
  84. }