StoreListing.test.tsx 14.6 KB
import { App, ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AccessProvider, saveUserInfo } from '@/access';
import StoreListing from './index';

const api = vi.hoisted(() => ({
  listStores: vi.fn(),
  getStore: vi.fn(),
  getChanges: vi.fn(),
  getColumnConfig: vi.fn(),
  saveColumnConfig: vi.fn(),
  exportStores: vi.fn(),
}));
vi.mock('@/api', () => ({ store: api }));

const rows = [
  {
    listingId: 101,
    storeName: '同名门店',
    merchantNo: 'M001',
    businessScene: '售后会员权益升级',
    effectiveTime: '2026-10-08T09:00:00',
    changeCount: 2,
    costTotal: '1500.00',
  },
  {
    listingId: 102,
    storeName: '同名门店',
    merchantNo: 'M001',
    businessScene: '售前延保',
    effectiveTime: '2026-10-07T09:00:00',
    changeCount: 1,
    costTotal: '1500.00',
  },
];
const columns = ['storeName', 'merchantNo', 'businessScene', 'effectiveTime', 'changeCount'];
const queryClients: QueryClient[] = [];

function renderPage(permissions = ['store:list:view', 'store:list:export']) {
  saveUserInfo({ permCodes: permissions, dataScope: 3 });
  const client = new QueryClient({
    defaultOptions: { queries: { retry: false, staleTime: 30_000 }, mutations: { retry: false } },
  });
  queryClients.push(client);
  return render(
    <ConfigProvider locale={zhCN}>
      <App>
        <QueryClientProvider client={client}>
          <AccessProvider>
            <StoreListing />
          </AccessProvider>
        </QueryClientProvider>
      </App>
    </ConfigProvider>,
  );
}

beforeEach(() => {
  vi.clearAllMocks();
  api.listStores.mockImplementation(async (params) => ({
    records: rows,
    total: 42,
    current: params.current ?? 1,
    size: params.size ?? 20,
    pages: 3,
  }));
  api.getColumnConfig.mockResolvedValue({ columns });
  api.saveColumnConfig.mockImplementation(async (next) => {
    api.getColumnConfig.mockResolvedValue({ columns: next });
  });
  api.exportStores.mockResolvedValue(undefined);
  api.getStore.mockImplementation(async (id) => ({
    ...rows.find((row) => row.listingId === id),
    items: [],
    approvalLogs: [],
    changeHistory: [],
    status: 'APPROVED',
  }));
  api.getChanges.mockResolvedValue([]);
  vi.stubGlobal(
    'ResizeObserver',
    class {
      observe() {}
      disconnect() {}
      unobserve() {}
    },
  );
});

afterEach(() => {
  cleanup();
  queryClients.forEach((client) => client.clear());
  queryClients.length = 0;
  localStorage.clear();
  vi.unstubAllGlobals();
});

describe('门店列表', () => {
  it('本地业务场景可筛选且导出沿用同一实际中文值', async () => {
    renderPage();
    fireEvent.mouseDown(await screen.findByLabelText('业务场景'));
    fireEvent.click(
      await screen.findByText('售后众筹', { selector: '.ant-select-item-option-content' }),
    );
    fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
    await waitFor(() =>
      expect(api.listStores).toHaveBeenLastCalledWith(
        expect.objectContaining({ businessScene: '售后众筹', current: 1 }),
      ),
    );
    const exportButton = screen.getByRole('button', { name: /导\s*出/ });
    await waitFor(() => expect(exportButton).not.toBeDisabled());
    fireEvent.click(exportButton);
    await waitFor(() =>
      expect(api.exportStores).toHaveBeenCalledWith(
        expect.objectContaining({ businessScene: '售后众筹' }),
      ),
    );
    expect(screen.queryByText('业务场景加载失败')).not.toBeInTheDocument();
  });

  it('提交真实筛选参数,翻页保留筛选,重置同时清空表单与请求', async () => {
    renderPage();
    const input = await screen.findByLabelText('门店名称');
    fireEvent.change(input, { target: { value: '  同名  ' } });
    fireEvent.change(screen.getByLabelText('门店商户号'), { target: { value: 'M001' } });
    fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
    await waitFor(() =>
      expect(api.listStores).toHaveBeenLastCalledWith(
        expect.objectContaining({ current: 1, size: 20, storeName: '同名', merchantNo: 'M001' }),
      ),
    );
    fireEvent.click(screen.getByTitle('2'));
    await waitFor(() =>
      expect(api.listStores).toHaveBeenLastCalledWith(
        expect.objectContaining({ current: 2, storeName: '同名' }),
      ),
    );
    fireEvent.click(screen.getByRole('button', { name: /重\s*置/ }));
    await waitFor(() =>
      expect(api.listStores).toHaveBeenLastCalledWith(
        expect.objectContaining({ current: 1, size: 20 }),
      ),
    );
    expect(api.listStores.mock.lastCall?.[0].storeName).toBeUndefined();
    expect(api.listStores.mock.lastCall?.[0].merchantNo).toBeUndefined();
    expect(screen.getByLabelText('门店名称')).toHaveValue('');
    expect(screen.getByLabelText('门店商户号')).toHaveValue('');
    expect(screen.getByText('数据可见范围:本部门')).toBeInTheDocument();
  });

  it('服务端排序并仅导出当前筛选与排序,不传分页', async () => {
    renderPage();
    const input = await screen.findByLabelText('门店名称');
    fireEvent.change(input, { target: { value: '目标门店' } });
    fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
    await waitFor(() => expect(api.listStores.mock.lastCall?.[0].storeName).toBe('目标门店'));
    fireEvent.click(screen.getByRole('columnheader', { name: /变更次数/ }));
    await waitFor(() =>
      expect(api.listStores.mock.lastCall?.[0]).toEqual(
        expect.objectContaining({ sortField: 'changeCount', sortOrder: 'asc' }),
      ),
    );
    const exportButton = screen.getByRole('button', { name: /导\s*出/ });
    await waitFor(() => expect(exportButton).not.toBeDisabled());
    fireEvent.click(exportButton);
    await waitFor(() =>
      expect(api.exportStores).toHaveBeenCalledWith({
        storeName: '目标门店',
        sortField: 'changeCount',
        sortOrder: 'asc',
      }),
    );
  });

  it('按所点击行的 listingId 打开详情,区分同门店的不同业务场景', async () => {
    renderPage();
    const buttons = await screen.findAllByRole('button', { name: '查看详情' });
    fireEvent.click(buttons[1]);
    await waitFor(() => expect(api.getStore).toHaveBeenCalledWith(102));
    await waitFor(() => expect(api.getChanges).toHaveBeenCalledWith(102));
    const drawer = await screen.findByRole('dialog');
    await waitFor(() => expect(within(drawer).getAllByText('售前延保').length).toBeGreaterThan(0));
    expect(within(drawer).queryByText('售后会员权益升级')).not.toBeInTheDocument();
  });

  it('点击门店名称打开对应记录详情', async () => {
    renderPage();
    const names = await screen.findAllByRole('button', { name: '同名门店' });
    fireEvent.click(names[0]);
    await waitFor(() => expect(api.getStore).toHaveBeenCalledWith(101));
    const drawer = await screen.findByRole('dialog');
    await waitFor(() =>
      expect(within(drawer).getAllByText('售后会员权益升级').length).toBeGreaterThan(0),
    );
  });

  it('取消列配置不写入,保存按勾选顺序提交并使用服务端配置', async () => {
    renderPage();
    fireEvent.click(await screen.findByRole('button', { name: '列配置' }));
    let dialog = await screen.findByRole('dialog');
    fireEvent.click(within(dialog).getByLabelText('门店商户号'));
    fireEvent.click(within(dialog).getByRole('button', { name: /取\s*消/ }));
    expect(api.saveColumnConfig).not.toHaveBeenCalled();
    expect(screen.getByRole('columnheader', { name: '门店商户号' })).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: '列配置' }));
    dialog = await screen.findByRole('dialog');
    fireEvent.click(within(dialog).getByLabelText('门店商户号'));
    fireEvent.click(within(dialog).getByRole('button', { name: '上移上架时间' }));
    fireEvent.click(within(dialog).getByRole('button', { name: /保\s*存/ }));
    await waitFor(() =>
      expect(api.saveColumnConfig).toHaveBeenCalledWith([
        'storeName',
        'effectiveTime',
        'businessScene',
        'changeCount',
      ]),
    );
    await waitFor(() =>
      expect(screen.queryByRole('columnheader', { name: '门店商户号' })).not.toBeInTheDocument(),
    );
  });

  it('列配置读取失败可重试且不能用默认值覆盖服务器', async () => {
    api.getColumnConfig.mockRejectedValue(new Error('配置读取失败'));
    renderPage();
    fireEvent.click(await screen.findByRole('button', { name: '列配置' }));
    const dialog = await screen.findByRole('dialog');
    expect(await within(dialog).findByText(/配置读取失败/)).toBeInTheDocument();
    expect(within(dialog).getByRole('button', { name: /保\s*存/ })).toBeDisabled();
    expect(api.saveColumnConfig).not.toHaveBeenCalled();
    api.getColumnConfig.mockResolvedValue({ columns });
    fireEvent.click(within(dialog).getByRole('button', { name: '重新加载列配置' }));
    await waitFor(() =>
      expect(within(dialog).getByRole('button', { name: /保\s*存/ })).not.toBeDisabled(),
    );
  });

  it('忽略未知列并允许只保留门店名称,必选列不能取消', async () => {
    api.getColumnConfig.mockResolvedValue({ columns: ['retiredColumn', 'changeCount'] });
    renderPage();
    fireEvent.click(await screen.findByRole('button', { name: '列配置' }));
    const dialog = await screen.findByRole('dialog');
    expect(within(dialog).getByLabelText('门店名称')).toBeChecked();
    expect(within(dialog).getByLabelText('门店名称')).toBeDisabled();
    fireEvent.click(within(dialog).getByLabelText('变更次数'));
    fireEvent.click(within(dialog).getByRole('button', { name: /保\s*存/ }));
    await waitFor(() => expect(api.saveColumnConfig).toHaveBeenCalledWith(['storeName']));
    await waitFor(() =>
      expect(screen.queryByRole('columnheader', { name: /变更次数/ })).not.toBeInTheDocument(),
    );
    expect(screen.getByRole('columnheader', { name: '门店名称' })).toBeInTheDocument();
    expect(screen.getByRole('columnheader', { name: '操作' })).toBeInTheDocument();
  });

  it('请求失败保留筛选值,重新加载使用相同条件', async () => {
    renderPage();
    const input = await screen.findByLabelText('门店名称');
    api.listStores.mockRejectedValueOnce(new Error('门店查询失败'));
    fireEvent.change(input, { target: { value: '待查询门店' } });
    fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
    expect(await screen.findByText('门店查询失败')).toBeInTheDocument();
    expect(screen.getByLabelText('门店名称')).toHaveValue('待查询门店');
    let finishRetry: () => void = () => undefined;
    api.listStores.mockImplementationOnce(
      () =>
        new Promise((resolve) => {
          finishRetry = () => resolve({ records: rows, total: 2, current: 1, size: 20, pages: 1 });
        }),
    );
    fireEvent.click(screen.getByRole('button', { name: '重新加载列表' }));
    await waitFor(() => expect(api.listStores).toHaveBeenCalledTimes(3));
    expect(screen.getByLabelText('门店名称')).toHaveValue('待查询门店');
    finishRetry();
    await waitFor(() => expect(screen.queryByText('门店查询失败')).not.toBeInTheDocument());
    expect(api.listStores).toHaveBeenLastCalledWith(
      expect.objectContaining({ storeName: '待查询门店', current: 1 }),
    );
    expect(await screen.findAllByRole('button', { name: '查看详情' })).toHaveLength(2);
  });

  it('导出失败展示原因,超过五万条时阻止请求', async () => {
    api.exportStores.mockRejectedValueOnce(new Error('导出暂不可用'));
    const view = renderPage();
    fireEvent.click(await screen.findByRole('button', { name: /导\s*出/ }));
    expect(await screen.findByText('导出暂不可用')).toBeInTheDocument();
    view.unmount();
    api.listStores.mockResolvedValue({ records: rows, total: 50_001, current: 1, size: 20 });
    renderPage();
    const button = await screen.findByRole('button', { name: /导\s*出/ });
    expect(button).toBeDisabled();
    expect(api.exportStores).toHaveBeenCalledTimes(1);
    expect(screen.getByText(/超过 50,000 条/)).toBeInTheDocument();
  });

  it('导出进行中改变筛选条件仍阻止重复导出', async () => {
    let completeExport: () => void = () => undefined;
    api.exportStores.mockImplementation(
      () =>
        new Promise<void>((resolve) => {
          completeExport = resolve;
        }),
    );
    renderPage();
    fireEvent.click(await screen.findByRole('button', { name: /导\s*出/ }));
    await waitFor(() => expect(api.exportStores).toHaveBeenCalledTimes(1));
    fireEvent.change(screen.getByLabelText('门店名称'), { target: { value: '另一个筛选' } });
    fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
    await waitFor(() => expect(api.listStores.mock.lastCall?.[0].storeName).toBe('另一个筛选'));
    expect(screen.getByRole('button', { name: /正在导出/ })).toBeDisabled();
    expect(api.exportStores).toHaveBeenCalledTimes(1);
    completeExport();
    await waitFor(() => expect(screen.getByRole('button', { name: /导\s*出/ })).not.toBeDisabled());
  });

  it('有查看权限而无导出权限时隐藏导出操作', async () => {
    renderPage(['store:list:view']);
    await screen.findByLabelText('门店名称');
    expect(screen.queryByRole('button', { name: /导\s*出/ })).not.toBeInTheDocument();
    expect(screen.getAllByRole('button', { name: '查看详情' })).toHaveLength(2);
  });

  it('无页面查看权限时显示403且不发起数据请求', async () => {
    renderPage([]);
    expect(await screen.findByText('无门店列表访问权限')).toBeInTheDocument();
    expect(api.listStores).not.toHaveBeenCalled();
    expect(api.getColumnConfig).not.toHaveBeenCalled();
    expect(api.getStore).not.toHaveBeenCalled();
  });

  it('总数减少造成当前页越界时自动回到最后有效页', async () => {
    api.listStores.mockImplementation(async (params) => ({
      records: params.current === 3 ? [] : rows,
      total: params.current === 1 ? 61 : 21,
      current: params.current,
      size: params.size,
      pages: params.current === 1 ? 4 : 2,
    }));
    renderPage();
    fireEvent.click(await screen.findByTitle('3'));
    await waitFor(() =>
      expect(api.listStores).toHaveBeenLastCalledWith(
        expect.objectContaining({ current: 2, size: 20 }),
      ),
    );
    expect(await screen.findAllByRole('button', { name: '查看详情' })).toHaveLength(2);
  });
});