ChannelCodeViewDrawer.test.tsx 9.58 KB
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { App } from '../../App';
import { getChannelQRCodeList, getChannelQRCodeDetail, type ChannelQRCodeListItem, type ChannelQRCodeStatus, type ChannelQRCodeDetail } from '../../api/channelCode';
import { getPositionTagList } from '../../api/positionTag';

vi.mock('../../api/channelCode', () => ({
  getChannelQRCodeList: vi.fn(),
  getChannelQRCodeDetail: vi.fn(),
  createChannelQRCode: vi.fn(),
  updateChannelQRCode: vi.fn(),
  enableChannelQRCode: vi.fn(),
  disableChannelQRCode: vi.fn(),
  getPositionEmployees: vi.fn(),
  getEmployeeConfiguredQRCodes: vi.fn(),
  getEmployeeMounts: vi.fn(),
}));

vi.mock('../../api/positionTag', () => ({
  getPositionTagList: vi.fn(),
  createPositionTag: vi.fn(),
  updatePositionTag: vi.fn(),
  getPositionTagReferences: vi.fn(),
  deletePositionTag: vi.fn(),
}));

const mockChannelCodes: ChannelQRCodeListItem[] = [
  {
    qrcode_id: 1,
    qrcode_name: '店销顾问渠道活码',
    employee_name: '张小萌',
    position_name: '店销顾问',
    channel_code: 'DSC-QR-001',
    qrcode_url: 'https://picsum.photos/seed/store_sales/200/200',
    agent_count: 2,
    agent_names_preview: ['店销助手Agent', '管家Agent'],
    status: 'enable' as ChannelQRCodeStatus,
    created_at: '2026-05-10 09:00:00',
    operations: ['view', 'edit', 'disable'],
  },
];

const mockChannelCodeDetail: ChannelQRCodeDetail = {
  qrcode_id: 1,
  employee_id: 'emp_001',
  qrcode_name: '店销顾问渠道活码',
  employee_name: '张小萌',
  position_code: 'store_sales',
  position_name: '店销顾问',
  channel_code: 'DSC-QR-001',
  qrcode_url: 'https://picsum.photos/seed/store_sales/200/200',
  agent_ids: [1, 2],
  agent_names: ['店销助手Agent', '管家Agent'],
  status: 'enable' as ChannelQRCodeStatus,
  remark: '用于门店销售渠道客户接入',
  welcome_message: '欢迎咨询门店产品与服务',
  created_at: '2026-05-10 09:00:00',
  created_by: 'admin',
};

const mockPositionTags = [
  { tag_id: 1, name: '店销顾问', code: 'store_sales', agent_count: 2, created_at: '2026-05-15' },
];

function renderChannelCodes(path = '/channel-codes') {
  window.localStorage.setItem('agent-admin-local-login', 'true');
  return render(
    <MemoryRouter initialEntries={[path]}>
      <App />
    </MemoryRouter>,
  );
}

async function findDrawer(title: string) {
  return waitFor(() => {
    const drawer = screen.getAllByText(title)
      .map((node) => node.closest('.t-drawer'))
      .find(Boolean);

    expect(drawer).toBeInTheDocument();
    return drawer as HTMLElement;
  });
}

function queryDrawer(title: string) {
  return screen.queryAllByText(title)
    .map((node) => node.closest('.t-drawer'))
    .find(Boolean);
}

describe('Channel code view drawer', () => {
  beforeEach(() => {
    window.localStorage.clear();
    vi.clearAllMocks();
    vi.mocked(getChannelQRCodeList).mockResolvedValue({
      list: mockChannelCodes,
      total: mockChannelCodes.length,
      page: 1,
      page_size: 10,
    });
    vi.mocked(getChannelQRCodeDetail).mockResolvedValue(mockChannelCodeDetail);
    vi.mocked(getPositionTagList).mockResolvedValue({
      list: mockPositionTags,
      total: mockPositionTags.length,
      page: 1,
      page_size: 100,
    });
  });

  it('opens drawer when clicking view action', async () => {
    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    expect(await findDrawer('店销顾问渠道活码')).toBeInTheDocument();
  });

  it('calls detail API when opening drawer', async () => {
    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    await waitFor(() => {
      expect(getChannelQRCodeDetail).toHaveBeenCalledWith(1);
    });
  });

  it('shows all detail fields in drawer', async () => {
    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    const drawer = await findDrawer('店销顾问渠道活码');
    expect(within(drawer).getByText('对应岗位')).toBeInTheDocument();
    expect(within(drawer).getByText('渠道编码')).toBeInTheDocument();
    expect(within(drawer).getByText('承接员工')).toBeInTheDocument();
    expect(within(drawer).getByText('张小萌')).toBeInTheDocument();
    expect(within(drawer).getByText('关联 Agent')).toBeInTheDocument();
    expect(within(drawer).getByText('状态')).toBeInTheDocument();
    expect(within(drawer).getByText('活码描述')).toBeInTheDocument();
    expect(within(drawer).getByText('用于门店销售渠道客户接入')).toBeInTheDocument();
    expect(within(drawer).getByText('自动欢迎语')).toBeInTheDocument();
    expect(within(drawer).getByText('欢迎咨询门店产品与服务')).toBeInTheDocument();

    const statusTag = within(drawer).getByText('启用');
    expect(statusTag.closest('.t-tag')).toBeInTheDocument();
  });

  it('shows QR code image', async () => {
    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    expect(await screen.findByRole('img', { name: '渠道活码二维码' })).toBeInTheDocument();
  });

  it('closes drawer and preserves list context', async () => {
    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
    expect(await findDrawer('店销顾问渠道活码')).toBeInTheDocument();

    const closeButton = screen.getByRole('button', { name: /^关闭(店销顾问渠道活码|渠道活码详情)$/ });
    fireEvent.click(closeButton);
    await waitFor(() => {
      expect(queryDrawer('店销顾问渠道活码')).toBeUndefined();
    });

    // List should still be visible
    expect(screen.getByRole('heading', { name: '渠道活码管理' })).toBeInTheDocument();
    expect(screen.getByText('店销顾问渠道活码')).toBeInTheDocument();
  });

  it('closes drawer via bottom close button', async () => {
    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));
    const drawer = await findDrawer('店销顾问渠道活码');

    // Footer close button uses "关闭" as text
    const footerCloseButton = within(drawer).getByRole('button', { name: '关闭' });
    fireEvent.click(footerCloseButton);
    await waitFor(() => {
      expect(queryDrawer('店销顾问渠道活码')).toBeUndefined();
    });
  });

  it('shows agent names as tags with unified color', async () => {
    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    const drawer = await findDrawer('店销顾问渠道活码');
    // Should display agent names as tags
    expect(within(drawer).getByText('店销助手Agent')).toBeInTheDocument();
    expect(within(drawer).getByText('管家Agent')).toBeInTheDocument();
  });

  it('shows dash when agent_names is empty', async () => {
    vi.mocked(getChannelQRCodeDetail).mockResolvedValueOnce({
      ...mockChannelCodeDetail,
      agent_names: [],
    });

    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    const drawer = await findDrawer('店销顾问渠道活码');
    // Should display "-" when no agent names
    const agentSection = within(drawer).getByText('关联 Agent').parentElement;
    expect(within(agentSection!).getByText('-')).toBeInTheDocument();
  });

  it('shows loading state while fetching detail', async () => {
    vi.mocked(getChannelQRCodeDetail).mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve(mockChannelCodeDetail), 100)));

    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    // Wait for drawer to open and show loading state
    await waitFor(() => {
      expect(screen.getByText('正在加载...')).toBeInTheDocument();
    });

    // Wait for loading to complete
    await screen.findByText('对应岗位');
  });

  it('shows error state and retry button when detail API fails', async () => {
    vi.mocked(getChannelQRCodeDetail).mockRejectedValueOnce(new Error('Network error'));
    vi.mocked(getChannelQRCodeDetail).mockResolvedValueOnce(mockChannelCodeDetail);

    renderChannelCodes();

    await screen.findByText('店销顾问渠道活码');
    fireEvent.click(screen.getByRole('button', { name: '查看店销顾问渠道活码' }));

    const drawer = await findDrawer('渠道活码详情');
    await waitFor(() => {
      expect(within(drawer).getByText('加载失败')).toBeInTheDocument();
    });
    expect(within(drawer).getByText('渠道活码详情加载失败,请重试')).toBeInTheDocument();

    const retryButton = within(drawer).getByRole('button', { name: '重试' });
    fireEvent.click(retryButton);

    // After retry, should show detail
    await screen.findByText('对应岗位');
    await waitFor(() => {
      expect(getChannelQRCodeDetail).toHaveBeenCalledTimes(2);
    });
  });
});