business-table.test.tsx 12.3 KB
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';

import { BusinessTable, type BusinessTableColumn } from '@gl/business-components';
import type { PrimaryTableCol } from 'tdesign-react';

type DemoRow = {
  id: number;
  name: string;
  status: string;
};

const demoColumns: PrimaryTableCol<DemoRow>[] = [
  { title: '名称', colKey: 'name' },
  {
    title: '状态',
    colKey: 'status',
    cell: ({ row }) => <span>{row.status}</span>,
  },
  {
    title: '操作',
    colKey: 'actions',
    cell: ({ row }) => (
      <button type="button" onClick={() => undefined}>
        编辑{row.name}
      </button>
    ),
  },
];

describe('BusinessTable', () => {
  it('renders configured columns, data and row actions from config', () => {
    const onEdit = vi.fn();
    const columns: PrimaryTableCol<DemoRow>[] = [
      { title: '名称', colKey: 'name' },
      {
        title: '状态',
        colKey: 'status',
        cell: ({ row }) => <span>{row.status}</span>,
      },
      {
        title: '操作',
        colKey: 'actions',
        cell: ({ row }) => (
          <button type="button" onClick={() => onEdit(row.id)}>
            编辑{row.name}
          </button>
        ),
      },
    ];

    render(
      <BusinessTable
        rowKey="id"
        columns={columns}
        data={[
          { id: 1, name: '示例一', status: '启用' },
          { id: 2, name: '示例二', status: '停用' },
        ]}
      />,
    );

    expect(screen.getByRole('columnheader', { name: '名称' })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: '状态' })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: '操作' })).toBeInTheDocument();
    expect(screen.getByText('示例一')).toBeInTheDocument();
    expect(screen.getByText('启用')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: '编辑示例一' }));
    expect(onEdit).toHaveBeenCalledWith(1);
  });

  it('renders the normal empty state with title and no default action', () => {
    render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
      />,
    );

    expect(screen.getByText('暂无数据')).toBeInTheDocument();
    expect(screen.queryByText('请先创建项目')).not.toBeInTheDocument();
    expect(screen.queryByText('未能查询到符合条件的资源')).not.toBeInTheDocument();
    expect(screen.queryByText('未找到匹配结果')).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
  });

  it('renders the filtered empty state without description or clear filter action', () => {
    render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
        hasFilter
        filteredEmptyState={{ onAction: vi.fn() }}
      />,
    );

    expect(screen.getByText('未找到匹配结果')).toBeInTheDocument();
    expect(screen.queryByText('请调整搜索或筛选条件')).not.toBeInTheDocument();
    expect(screen.queryByText('暂无数据')).not.toBeInTheDocument();
    expect(screen.queryByText('未能查询到符合条件的资源')).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();
  });

  it('renders the request failure state without retry action', () => {
    render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
        error
        errorState={{ onRetry: vi.fn() }}
      />,
    );

    expect(screen.getByText('请求失败')).toBeInTheDocument();
    expect(screen.queryByText('网络不可用')).not.toBeInTheDocument();
    expect(screen.queryByText('请检查网络连接后重试')).not.toBeInTheDocument();
    expect(screen.queryByText('接口请求失败,请稍后重试')).not.toBeInTheDocument();
    expect(screen.queryByText('数据请求失败,请稍后重试')).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button')).not.toBeInTheDocument();
  });

  it('renders the forbidden state with description and permission action', () => {
    const onRequestPermission = vi.fn();

    render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
        error
        errorState={{ kind: 'forbidden', onRetry: onRequestPermission }}
      />,
    );

    expect(screen.getByText('权限受限')).toBeInTheDocument();
    expect(screen.getByText('当前账号暂无访问权限')).toBeInTheDocument();
    const requestButton = screen.getByRole('button', { name: '申请权限' });
    expect(requestButton).toHaveClass('t-button--theme-primary');
    expect(requestButton).toHaveClass('t-button--variant-base');
    fireEvent.click(requestButton);
    expect(onRequestPermission).toHaveBeenCalledTimes(1);
  });

  it('uses the centered empty-state layout for normal, filtered and failure states', () => {
    const { container, rerender } = render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
      />,
    );

    expect(container.querySelector('[class*="emptyState"]')).toBeInTheDocument();

    rerender(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
        hasFilter
        filteredEmptyState={{ onAction: vi.fn() }}
      />,
    );

    expect(container.querySelector('[class*="emptyState"]')).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '清空筛选' })).not.toBeInTheDocument();

    rerender(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
        error
        errorState={{ onRetry: vi.fn() }}
      />,
    );

    expect(container.querySelector('[class*="emptyState"]')).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '重试' })).not.toBeInTheDocument();
  });

  it('uses the business loading style while preserving the table structure', async () => {
    const { container } = render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[]}
        loading
      />,
    );

    expect(screen.getByRole('columnheader', { name: '名称' })).toBeInTheDocument();
    expect(screen.queryByText('暂无数据')).not.toBeInTheDocument();

    await waitFor(() => {
      expect(screen.getByText('加载中')).toBeInTheDocument();
    });
    expect(container.querySelector('[class*="businessTableLoading"]')).toBeInTheDocument();
  });

  it('passes table display and row interaction props through to TDesign Table', () => {
    const onRowClick = vi.fn();

    const { container } = render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[
          { id: 1, name: '示例一', status: '启用' },
        ]}
        tableClassName="demo-table"
        hover
        maxHeight={240}
        rowClassName={({ row }) => (row.id === 1 ? 'demo-row' : '')}
        onRowClick={onRowClick}
      />,
    );

    expect(container.querySelector('.t-table')).toHaveClass('t-table--hoverable', 'demo-table');
    expect(container.querySelector('[style*="max-height"]')).toHaveStyle({ maxHeight: '240px' });

    fireEvent.click(screen.getByRole('row', { name: /示例一/ }));
    expect(onRowClick).toHaveBeenCalledTimes(1);
    expect(screen.getByText('示例一').closest('tr')).toHaveClass('demo-row');
  });

  it('does not add tooltip to plain text cells by default', () => {
    const longName = '这是一段很长的表格文本内容,用来验证通用表格列的省略和悬浮展示';
    const { container } = render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[
          { id: 1, name: longName, status: '启用' },
        ]}
      />,
    );

    const textCell = screen.getByText(longName);
    expect(textCell.className).not.toContain('cellText');
    expect(container.querySelector('[class*="cellTooltipContent"]')).not.toBeInTheDocument();
  });

  it('truncates explicitly configured text cells and shows full content with TDesign Tooltip', async () => {
    const longName = '这是一段很长的表格文本内容,用来验证通用表格列的省略和悬浮展示';
    const columns: BusinessTableColumn<DemoRow>[] = [
      { title: '名称', colKey: 'name', ellipsisTooltip: true },
      {
        title: '状态',
        colKey: 'status',
        cell: ({ row }) => <span>{row.status}</span>,
      },
    ];
    const { container } = render(
      <BusinessTable
        rowKey="id"
        columns={columns}
        data={[
          { id: 1, name: longName, status: '启用' },
        ]}
      />,
    );

    const textCell = screen.getByText(longName);
    expect(textCell.className).toContain('cellText');
    expect(screen.getByText('启用').className).not.toContain('cellText');

    fireEvent.mouseEnter(textCell);

    await waitFor(() => {
      const tooltipContent = document.body.querySelector('[class*="cellTooltipContent"]');
      expect(tooltipContent).toBeInTheDocument();
      if (!tooltipContent) throw new Error('Tooltip content should exist');
      expect(tooltipContent).toHaveTextContent(longName);
      expect(tooltipContent).toHaveStyle({
        width: '200px',
        maxWidth: '200px',
        whiteSpace: 'normal',
      });
      expect(tooltipContent.className).toContain('cellTooltipContent');
    });
    expect(container.querySelector('.t-table')).toBeInTheDocument();
  });

  it('uses explicit tooltip value for derived plain text columns', async () => {
    type AgentRow = {
      id: number;
      agents: string[];
    };
    const agentText = '小顾、设计助手、投放助手';
    const columns: BusinessTableColumn<AgentRow>[] = [
      {
        title: '关联 Agent',
        colKey: 'agents',
        ellipsisTooltip: true,
        tooltipValue: ({ agents }) => (agents.length > 0 ? agents.join('、') : '-'),
      },
    ];

    render(
      <BusinessTable
        rowKey="id"
        columns={columns}
        data={[{ id: 1, agents: ['小顾', '设计助手', '投放助手'] }]}
      />,
    );

    const textCell = screen.getByText(agentText);
    expect(textCell.className).toContain('cellText');

    fireEvent.mouseEnter(textCell);

    await waitFor(() => {
      const tooltipContent = document.body.querySelector('[class*="cellTooltipContent"]');
      expect(tooltipContent).toBeInTheDocument();
      expect(tooltipContent).toHaveTextContent(agentText);
    });
  });

  it('does not render tooltip for explicitly configured empty text cells', () => {
    const columns: BusinessTableColumn<DemoRow>[] = [
      { title: '名称', colKey: 'name', ellipsisTooltip: true },
    ];
    const { container } = render(
      <BusinessTable
        rowKey="id"
        columns={columns}
        data={[
          { id: 1, name: '', status: '启用' },
          { id: 2, name: '   ', status: '启用' },
          { id: 3, name: '-', status: '启用' },
          { id: 4, name: '实际说明', status: '启用' },
        ]}
      />,
    );

    expect(screen.getAllByText('-')).toHaveLength(3);
    expect(screen.getByText('实际说明').className).toContain('cellText');
    expect(container.querySelectorAll('[class*="cellText"]')).toHaveLength(1);
    expect(container.querySelector('[class*="cellTooltipContent"]')).not.toBeInTheDocument();
  });

  it('renders pagination, honors totalLabel and can disable pagination', () => {
    const { container, rerender } = render(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[
          { id: 1, name: '示例一', status: '启用' },
        ]}
        pagination={{ current: 2, pageSize: 10, total: 35 }}
        totalLabel="共 35 条"
      />,
    );

    expect(container.querySelector('.t-pagination')).toBeInTheDocument();
    expect(screen.getAllByText('共 35 条数据')).toHaveLength(1);
    expect(screen.queryByText('共 35 条')).not.toBeInTheDocument();

    rerender(
      <BusinessTable
        rowKey="id"
        columns={demoColumns}
        data={[
          { id: 1, name: '示例一', status: '启用' },
        ]}
        pagination={false}
        totalLabel="共 35 条"
      />,
    );

    expect(container.querySelector('.t-pagination')).not.toBeInTheDocument();
    expect(screen.getByText('共 35 条').tagName).toBe('SPAN');
  });
});