StoreListing.test.tsx 17.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
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 { AccessTestProvider } from '@/test/AccessTestProvider';
import StoreListing from './index';

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

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']) {
  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}>
          <AccessTestProvider permCodes={permissions}>
            <StoreListing />
          </AccessTestProvider>
        </QueryClientProvider>
      </App>
    </ConfigProvider>,
  );
}

beforeEach(() => {
  vi.clearAllMocks();
  api.listScenes.mockResolvedValue([]);
  api.listGoodsCategories.mockResolvedValue({
    records: [],
    total: 0,
    current: 1,
    size: 20,
    pages: 0,
  });
  api.listStores.mockImplementation(async (params) => ({
    records: rows,
    total: 42,
    current: params.current ?? 1,
    size: params.size ?? 10,
    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 () => {
    api.listScenes.mockResolvedValue([{ id: 11, name: '新能源车交付' }]);
    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();
    expect(api.listGoodsCategories).not.toHaveBeenCalled();
  });

  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: 10, 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: 10 }),
      ),
    );
    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.queryByText(/数据可见范围/)).not.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('目标门店'));
    const requestCount = api.listStores.mock.calls.length;
    for (const name of ['上架时间', '变更次数']) {
      const header = screen.getByRole('columnheader', { name });
      expect(header).not.toHaveAttribute('aria-sort');
      expect(header).not.toHaveAttribute('tabindex');
      fireEvent.click(header);
    }
    expect(api.listStores).toHaveBeenCalledTimes(requestCount);
    expect(screen.getAllByRole('columnheader').map((header) => header.textContent)).toEqual([
      '门店名称',
      '门店商户号',
      '业务场景',
      '上架时间',
      '变更次数',
      '操作',
    ]);
    const exportButton = screen.getByRole('button', { name: /导\s*出/ });
    await waitFor(() => expect(exportButton).not.toBeDisabled());
    fireEvent.click(exportButton);
    await waitFor(() =>
      expect(api.exportStores).toHaveBeenCalledWith({
        storeName: '目标门店',
        sortField: 'effectiveDate',
        sortOrder: 'desc',
      }),
    );
  });

  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();
    await screen.findAllByText('同名门店');
    expect(screen.queryByRole('button', { name: '同名门店' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '查看同名门店变更历史' })).not.toBeInTheDocument();
    fireEvent.click(screen.getAllByRole('button', { name: '变更历史' })[0]);
    await waitFor(() => expect(api.getChanges).toHaveBeenCalledWith(101));
    expect(await screen.findByRole('tab', { name: '变更历史' })).toHaveAttribute(
      'aria-selected',
      'true',
    );
  });

  it('后端乱序与重复列按原型顺序展示,未配置列保持隐藏', async () => {
    api.getColumnConfig.mockResolvedValue({
      columns: [
        'changeCount',
        'effectiveTime',
        'businessScene',
        'effectiveTime',
        'storeName',
        'changeCount',
        'retiredColumn',
      ],
    });
    renderPage();
    await screen.findAllByText('同名门店');
    await waitFor(() =>
      expect(screen.queryByRole('columnheader', { name: '门店商户号' })).not.toBeInTheDocument(),
    );
    expect(screen.getAllByRole('columnheader').map((header) => header.textContent)).toEqual([
      '门店名称',
      '业务场景',
      '上架时间',
      '变更次数',
      '操作',
    ]);
    expect(api.saveColumnConfig).not.toHaveBeenCalled();
  });

  it('列配置只控制显隐,取消不写入,保存和回显固定按原型顺序', async () => {
    api.getColumnConfig.mockResolvedValue({
      columns: ['changeCount', 'effectiveTime', 'storeName', 'businessScene', 'merchantNo'],
    });
    renderPage();
    fireEvent.click(await screen.findByRole('button', { name: '列配置' }));
    let dialog = await screen.findByRole('dialog');
    expect(within(dialog).queryAllByRole('button', { name: /上移|下移/ })).toHaveLength(0);
    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');
    expect(within(dialog).queryAllByRole('button', { name: /上移|下移/ })).toHaveLength(0);
    fireEvent.click(within(dialog).getByLabelText('门店商户号'));
    fireEvent.click(within(dialog).getByRole('button', { name: /保\s*存/ }));
    await waitFor(() =>
      expect(api.saveColumnConfig).toHaveBeenCalledWith([
        'storeName',
        'businessScene',
        'effectiveTime',
        'changeCount',
      ]),
    );
    await waitFor(() =>
      expect(screen.queryByRole('columnheader', { name: '门店商户号' })).not.toBeInTheDocument(),
    );
    expect(screen.getAllByRole('columnheader').map((header) => header.textContent)).toEqual([
      '门店名称',
      '业务场景',
      '上架时间',
      '变更次数',
      '操作',
    ]);
  });

  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: 10, 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: 10 });
    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();
    expect(api.listScenes).not.toHaveBeenCalled();
    expect(api.listGoodsCategories).not.toHaveBeenCalled();
  });

  it('仅有导出权限不能替代列表查看权限,也不显示导出操作', async () => {
    renderPage(['store:list:export']);
    expect(await screen.findByText('无门店列表访问权限')).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: /导\s*出/ })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '查看详情' })).not.toBeInTheDocument();
    expect(api.listStores).not.toHaveBeenCalled();
    expect(api.getColumnConfig).not.toHaveBeenCalled();
    expect(api.exportStores).not.toHaveBeenCalled();
  });

  it('总数减少造成当前页越界时自动回到最后有效页', async () => {
    api.listStores.mockImplementation(async (params) => ({
      records: params.current === 3 ? [] : rows,
      total: params.current === 1 ? 31 : 11,
      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: 10 }),
      ),
    );
    expect(await screen.findAllByRole('button', { name: '查看详情' })).toHaveLength(2);
  });
});