OfficialSiteMethodologyPage.test.tsx 8.64 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 { getMethodologyConfig, saveMethodologyConfig } from '../../api/methodology';
import { reportPageView } from '../../api/analytics';
import { App } from '../../App';

vi.mock('../../api/methodology', () => ({
  getMethodologyConfig: vi.fn(),
  saveMethodologyConfig: vi.fn(),
}));

vi.mock('../../api/analytics', () => ({
  reportPageView: vi.fn().mockResolvedValue({ success: true }),
  reportAnalyticsEvents: vi.fn().mockResolvedValue({ success: true }),
}));

const mockMethodologyConfig = {
  config_id: 'methodology_001',
  display_status: 'enable' as const,
  main_title: '四步打造可复用的岗位 Agent',
  sub_title: '从目标澄清到上线复盘,帮助团队沉淀一套稳定可复制的方法论。',
  steps: [
    { step_id: 's1', step_icon: 'https://cdn.example.com/icon1.png', step_name: '需求澄清', step_order: 1, step_image: 'https://cdn.example.com/image1.png' },
    { step_id: 's2', step_icon: 'https://cdn.example.com/icon2.png', step_name: '方案设计', step_order: 2, step_image: 'https://cdn.example.com/image2.png' },
    { step_id: 's3', step_icon: 'https://cdn.example.com/icon3.png', step_name: '上线复盘', step_order: 3, step_image: 'https://cdn.example.com/image3.png' },
  ],
  updated_at: '2026-05-16T10:00:00Z',
};

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

describe('OfficialSiteMethodologyPage form and steps', () => {
  beforeEach(() => {
    window.localStorage.clear();
    vi.clearAllMocks();
    vi.mocked(getMethodologyConfig).mockResolvedValue(mockMethodologyConfig);
    vi.mocked(saveMethodologyConfig).mockResolvedValue({ config_id: 'methodology_001', updated_at: '2026-05-16T12:00:00Z' });
    vi.mocked(reportPageView).mockResolvedValue({ success: true });
  });

  it('renders the core fields and hydrates the normal mock config', async () => {
    renderMethodology();

    expect(screen.getByText('加载中...')).toBeInTheDocument();

    await waitFor(() => {
      expect(screen.getByRole('switch', { name: '展示状态' })).toHaveAttribute('aria-checked', 'true');
    });

    expect(screen.getByLabelText('主标题')).toHaveValue('四步打造可复用的岗位 Agent');
    expect(screen.getByLabelText('副标题')).toHaveValue('从目标澄清到上线复盘,帮助团队沉淀一套稳定可复制的方法论。');

    const cards = screen.getAllByTestId('methodology-step-card');
    expect(cards).toHaveLength(3);
    expect(within(cards[0]).getByLabelText('步骤3名称')).toHaveValue('上线复盘');
    expect(within(cards[1]).getByLabelText('步骤2名称')).toHaveValue('方案设计');
    expect(within(cards[2]).getByLabelText('步骤1名称')).toHaveValue('需求澄清');
  });

  it('keeps the page header fixed while the methodology content scrolls independently', async () => {
    renderMethodology();

    await waitFor(() => {
      expect(screen.getByRole('heading', { name: '方法论展示配置' })).toBeInTheDocument();
    });

    const pageHeader = screen.getByRole('heading', { name: '方法论展示配置' }).closest('header') as HTMLElement;
    const pageRoot = pageHeader.closest('section') as HTMLElement;
    const scrollArea = pageRoot.querySelector('[data-testid="methodology-page-scroll-area"]') as HTMLElement;

    expect(pageRoot).toHaveClass('h-full', 'min-h-0', 'overflow-hidden');
    expect(pageHeader).toHaveClass('shrink-0', 'bg-[var(--gl-color-bg-container)]');
    expect(scrollArea).toHaveClass('min-h-0', 'flex-1', 'overflow-y-auto');
    expect(within(pageHeader).getByRole('button', { name: '保存配置' })).toBeInTheDocument();
    expect(within(scrollArea).getByLabelText('主标题')).toHaveValue('四步打造可复用的岗位 Agent');
  });

  it('supports disabled display status and empty-step fixtures', async () => {
    vi.mocked(getMethodologyConfig).mockResolvedValueOnce({
      ...mockMethodologyConfig,
      display_status: 'disable',
    });
    const disabledView = renderMethodology('/official-site/methodology');

    await waitFor(() => {
      expect(screen.getByRole('switch', { name: '展示状态' })).toHaveAttribute('aria-checked', 'false');
    });

    disabledView.unmount();

    vi.mocked(getMethodologyConfig).mockResolvedValueOnce({
      ...mockMethodologyConfig,
      steps: [],
    });
    renderMethodology('/official-site/methodology');

    await waitFor(() => {
      expect(screen.getByText('当前还没有方法论步骤')).toBeInTheDocument();
    });

    expect(screen.getByRole('button', { name: '添加步骤' })).toBeInTheDocument();
  });

  it('validates required titles and enabled-empty-steps before saving', async () => {
    renderMethodology();

    await waitFor(() => {
      expect(screen.getByLabelText('主标题')).toBeInTheDocument();
    });

    fireEvent.change(screen.getByLabelText('主标题'), { target: { value: '' } });
    fireEvent.change(screen.getByLabelText('副标题'), { target: { value: '' } });
    fireEvent.click(screen.getByRole('button', { name: '删除步骤 1' }));
    fireEvent.click(screen.getByRole('button', { name: '删除步骤 1' }));
    fireEvent.click(screen.getByRole('button', { name: '删除步骤 1' }));
    fireEvent.click(screen.getByRole('button', { name: '保存配置' }));

    expect(screen.getByText('请输入主标题')).toBeInTheDocument();
    expect(screen.getByText('请输入副标题')).toBeInTheDocument();
    expect(screen.getByText('至少添加一个方法论步骤')).toBeInTheDocument();
  });

  it('supports step add, delete, move, and order maintenance', async () => {
    renderMethodology();

    await waitFor(() => {
      expect(screen.getAllByTestId('methodology-step-card')).toHaveLength(3);
    });

    fireEvent.click(screen.getByRole('button', { name: '添加步骤' }));

    let cards = screen.getAllByTestId('methodology-step-card');
    expect(cards).toHaveLength(4);
    expect(within(cards[0]).getByLabelText('步骤4名称')).toHaveValue('');
    expect(within(cards[1]).getByLabelText('步骤3名称')).toHaveValue('上线复盘');

    fireEvent.click(within(cards[1]).getByRole('button', { name: '下移步骤 3' }));

    cards = screen.getAllByTestId('methodology-step-card');
    expect(within(cards[1]).getByLabelText('步骤3名称')).toHaveValue('方案设计');
    expect(within(cards[2]).getByLabelText('步骤2名称')).toHaveValue('上线复盘');

    fireEvent.click(within(cards[2]).getByRole('button', { name: '上移步骤 2' }));

    cards = screen.getAllByTestId('methodology-step-card');
    expect(within(cards[1]).getByLabelText('步骤3名称')).toHaveValue('上线复盘');
    expect(within(cards[2]).getByLabelText('步骤2名称')).toHaveValue('方案设计');

    fireEvent.click(within(cards[0]).getByRole('button', { name: '删除步骤 4' }));

    cards = screen.getAllByTestId('methodology-step-card');
    expect(cards).toHaveLength(3);
    expect(within(cards[0]).getByLabelText('步骤3名称')).toHaveValue('上线复盘');
    expect(within(cards[1]).getByLabelText('步骤2名称')).toHaveValue('方案设计');

    fireEvent.click(screen.getByRole('button', { name: '保存配置' }));

    await waitFor(() => {
      expect(saveMethodologyConfig).toHaveBeenCalled();
    });
    expect(vi.mocked(saveMethodologyConfig).mock.calls[0][0].steps.map((step) => step.step_name)).toEqual([
      '需求澄清',
      '方案设计',
      '上线复盘',
    ]);
    expect(vi.mocked(saveMethodologyConfig).mock.calls[0][0].steps.map((step) => step.step_order)).toEqual([1, 2, 3]);
  });

  describe('analytics tracking', () => {
    it('reports page view after successful load', async () => {
      renderMethodology();

      await waitFor(() => {
        expect(screen.getByRole('switch', { name: '展示状态' })).toBeInTheDocument();
      });

      await waitFor(() => {
        expect(reportPageView).toHaveBeenCalledWith({
          page_type: 'official_site_methodology_config',
          session_id: expect.any(String),
          device_type: expect.stringMatching(/desktop|tablet|mobile/),
        });
      });
    });

    it('does not report page view on load failure', async () => {
      vi.mocked(getMethodologyConfig).mockRejectedValueOnce(new Error('Network error'));
      renderMethodology();

      await waitFor(() => {
        expect(screen.getByRole('alert', { name: '加载失败' })).toBeInTheDocument();
      });

      expect(reportPageView).not.toHaveBeenCalled();
    });
  });
});