test-utils.tsx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import type { ReactElement } from 'react';
  2. import { render, fireEvent } from '@testing-library/react';
  3. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  4. import { ThemeProvider } from '@/hooks/useTheme';
  5. export function makeTestQueryClient() {
  6. return new QueryClient({ defaultOptions: { queries: { retry: false } } });
  7. }
  8. export function renderWithProviders(ui: ReactElement, options?: { queryClient?: QueryClient }) {
  9. const queryClient = options?.queryClient ?? makeTestQueryClient();
  10. return render(
  11. <QueryClientProvider client={queryClient}>
  12. <ThemeProvider>{ui}</ThemeProvider>
  13. </QueryClientProvider>,
  14. );
  15. }
  16. export function fieldLabels(): string[] {
  17. return Array.from(document.querySelectorAll('.ant-form-item-label label'))
  18. .map((el) => (el.textContent ?? '').trim())
  19. .filter(Boolean);
  20. }
  21. function selectRootForField(fieldId: string): HTMLElement {
  22. const control = document.getElementById(fieldId);
  23. const select = control?.closest('.ant-select') as HTMLElement | null;
  24. if (!select) throw new Error(`Select not found for field id: ${fieldId}`);
  25. return select;
  26. }
  27. function openSelect(select: HTMLElement) {
  28. const target = (select.querySelector('.ant-select-selector') ?? select) as HTMLElement;
  29. fireEvent.mouseDown(target);
  30. }
  31. function openDropdownOptions(): string[] {
  32. return Array.from(
  33. document.querySelectorAll(
  34. '.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item-option',
  35. ),
  36. )
  37. .map((o) => (o.getAttribute('title') ?? o.textContent ?? '').trim())
  38. .filter(Boolean);
  39. }
  40. export function listSelectOptions(fieldId: string): string[] {
  41. const select = selectRootForField(fieldId);
  42. openSelect(select);
  43. const opts = openDropdownOptions();
  44. fireEvent.keyDown(select, { key: 'Escape' });
  45. return opts;
  46. }
  47. export function chooseSelectOption(fieldId: string, optionText: string) {
  48. const select = selectRootForField(fieldId);
  49. openSelect(select);
  50. const option = Array.from(document.querySelectorAll('.ant-select-item-option')).find(
  51. (o) => (o.getAttribute('title') ?? o.textContent ?? '').trim() === optionText,
  52. );
  53. if (!option) throw new Error(`Option '${optionText}' not found for field '${fieldId}'`);
  54. fireEvent.click(option);
  55. }