global-business-components.test.tsx 8.39 KB
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { MediaWall, SearchFilter, StatePlaceholder } from '@gl/business-components';

const searchFields = [
  { key: 'keyword', label: '关键词', type: 'input' as const, defaultValue: '项目' },
  { key: 'count', label: '数量', type: 'numberInput' as const },
  { key: 'status', label: '状态', type: 'select' as const, options: [{ label: '启用', value: 'enabled' }] },
];

function mockSearchFilterLayout({ containerWidth, fieldWidth = 284, actionsWidth = 220 }: {
  containerWidth: number;
  fieldWidth?: number;
  actionsWidth?: number;
}) {
  const originalClientWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientWidth');
  const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
  const originalScrollHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollHeight');
  const originalGetComputedStyle = window.getComputedStyle;

  Object.defineProperty(HTMLElement.prototype, 'clientWidth', {
    configurable: true,
    get() {
      if ((this as HTMLElement).dataset.searchFilterFlow === 'true') return containerWidth;
      return originalClientWidth?.get?.call(this) ?? 0;
    },
  });

  Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
    configurable: true,
    get() {
      const element = this as HTMLElement;
      if (element.dataset.searchFilterActions === 'true') return actionsWidth;
      if (element.dataset.fieldKey) return fieldWidth;
      return originalOffsetWidth?.get?.call(this) ?? 0;
    },
  });

  Object.defineProperty(HTMLElement.prototype, 'scrollHeight', {
    configurable: true,
    get() {
      return 96;
    },
  });

  window.getComputedStyle = ((element: Element) => {
    const style = originalGetComputedStyle(element);
    if ((element as HTMLElement).dataset.searchFilterFlow === 'true') {
      return new Proxy(style, {
        get(target, property, receiver) {
          if (property === 'columnGap') return '16px';
          if (property === 'rowGap') return '12px';
          return Reflect.get(target, property, receiver);
        },
      });
    }
    return style;
  }) as typeof window.getComputedStyle;

  return () => {
    if (originalClientWidth) Object.defineProperty(HTMLElement.prototype, 'clientWidth', originalClientWidth);
    if (originalOffsetWidth) Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
    if (originalScrollHeight) Object.defineProperty(HTMLElement.prototype, 'scrollHeight', originalScrollHeight);
    window.getComputedStyle = originalGetComputedStyle;
  };
}

describe('global business components', () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('keeps SearchFilter draft values until search and restores defaults on reset', () => {
    const onReset = vi.fn();
    const onSearch = vi.fn();

    render(
      <SearchFilter
        fields={searchFields}
        onReset={onReset}
        onSearch={onSearch}
      />,
    );

    fireEvent.change(screen.getByLabelText('数量'), { target: { value: '12a3' } });
    fireEvent.click(screen.getByRole('button', { name: '查询' }));

    expect(screen.getByLabelText('数量')).toHaveValue('123');
    expect(onSearch).toHaveBeenCalledWith({ keyword: '项目', count: '123', status: '' });

    fireEvent.change(screen.getByLabelText('关键词'), { target: { value: '合同' } });
    fireEvent.click(screen.getByRole('button', { name: '重置' }));

    expect(screen.getByLabelText('关键词')).toHaveValue('项目');
    expect(onReset).toHaveBeenCalledTimes(1);
  });

  it('renders SearchFilter actions after fields in query, reset, expand order', async () => {
    const restoreLayout = mockSearchFilterLayout({ containerWidth: 640, fieldWidth: 200, actionsWidth: 260 });

    render(
      <SearchFilter
        fields={[
          ...searchFields,
          { key: 'owner', label: '负责人', type: 'input' },
          { key: 'department', label: '部门', type: 'input' },
        ]}
      />,
    );

    await waitFor(() => expect(screen.getByRole('button', { name: '展开' })).toBeInTheDocument());

    const root = screen.getByLabelText('搜索过滤条件');
    const controls = within(root).getAllByRole('button').map((button) => button.textContent?.trim());
    expect(controls).toEqual(['查询', '重置', '展开']);

    restoreLayout();
  });

  it('does not show expand or collapse when fields and actions fit in two rows', async () => {
    const restoreLayout = mockSearchFilterLayout({ containerWidth: 920, fieldWidth: 200, actionsWidth: 220 });

    render(
      <SearchFilter
        fields={[
          ...searchFields,
          { key: 'owner', label: '负责人', type: 'input' },
          { key: 'department', label: '部门', type: 'input' },
        ]}
      />,
    );

    await waitFor(() => expect(screen.queryByRole('button', { name: '展开' })).not.toBeInTheDocument());
    expect(screen.queryByRole('button', { name: '收起' })).not.toBeInTheDocument();

    restoreLayout();
  });

  it('only folds when the responsive layout needs more than two rows', async () => {
    const restoreLayout = mockSearchFilterLayout({ containerWidth: 640, fieldWidth: 200, actionsWidth: 260 });

    render(
      <SearchFilter
        fields={[
          ...searchFields,
          { key: 'owner', label: '负责人', type: 'input' },
          { key: 'department', label: '部门', type: 'input' },
        ]}
      />,
    );

    await waitFor(() => expect(screen.getByRole('button', { name: '展开' })).toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: '展开' }));
    expect(screen.getByRole('button', { name: '收起' })).toBeInTheDocument();

    restoreLayout();
  });

  it('renders an empty range date field without TDesign value warnings', () => {
    const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);

    render(
      <SearchFilter
        fields={[
          { key: 'period', label: '统计周期', type: 'datePicker', range: true },
        ]}
      />,
    );

    expect(screen.getAllByLabelText('统计周期')).toHaveLength(2);
    expect(consoleError).not.toHaveBeenCalledWith(expect.stringContaining('TDesign DatePicker Error'));

    consoleError.mockRestore();
  });

  it('renders StatePlaceholder semantic roles and actions', () => {
    const onRetry = vi.fn();

    render(
      <>
        <StatePlaceholder state="empty" />
        <StatePlaceholder state="empty" title="加载中" description="正在加载" />
        <StatePlaceholder
          state="error"
          title="列表加载失败"
          description="请稍后重试"
          primaryAction={<button type="button" onClick={onRetry}>重新加载</button>}
        />
      </>,
    );

    expect(screen.getByRole('status', { name: '暂无数据' })).toBeInTheDocument();
    expect(screen.getByRole('status', { name: '加载中' })).toBeInTheDocument();
    expect(screen.getByText('正在加载')).toBeInTheDocument();
    expect(screen.getByRole('alert', { name: '列表加载失败' })).toBeInTheDocument();
    expect(screen.getByText('请稍后重试')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: '重新加载' }));
    expect(onRetry).toHaveBeenCalledTimes(1);
  });

  it('keeps MediaWall upload, preview, remove and hydrated image behavior', async () => {
    const onPreview = vi.fn();
    const onRemove = vi.fn();
    const onSelectFiles = vi.fn();
    const image = { id: 'cover', type: 'image' as const, src: '/cover.png', alt: '产品图片' };
    const file = new File(['demo'], 'demo.png', { type: 'image/png' });

    render(
      <MediaWall
        items={[image]}
        maxCount={2}
        onPreview={onPreview}
        onRemove={onRemove}
        onSelectFiles={onSelectFiles}
      />,
    );

    expect(document.querySelector(`img[src="${image.src}"]`)).toBeInTheDocument();

    fireEvent.click(document.querySelector('.t-icon-browse') as HTMLElement);
    fireEvent.click(document.querySelector('.t-icon-delete') as HTMLElement);

    expect(onPreview).toHaveBeenCalledWith(image);
    expect(onRemove).toHaveBeenCalledWith(image);

    const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
    fireEvent.change(fileInput, { target: { files: [file] } });

    await waitFor(() => {
      expect(onSelectFiles).toHaveBeenCalledWith([file]);
    });
  });
});