test-utils.tsx 1.8 KB

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