officialSiteApi.test.ts 6.81 KB
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fetchOfficialSiteHome } from '../api/official-site';
import { ApiError } from '../api/types';
import type { HomeData } from '../types/home';

type BackendQrcodeStatus = 'enable' | 'disable';

interface BackendHomeData extends Omit<HomeData, 'tabs'> {
  tabs: Array<
    Omit<HomeData['tabs'][number], 'qrcode_status'> & {
      qrcode_status: BackendQrcodeStatus;
    }
  >;
}

describe('首页 API 模块测试', () => {
  const originalFetch = globalThis.fetch;
  let mockFetch: ReturnType<typeof vi.fn>;

  beforeEach(() => {
    mockFetch = vi.fn();
    (globalThis as unknown as { fetch: unknown }).fetch = mockFetch;
  });

  afterEach(() => {
    (globalThis as unknown as { fetch: unknown }).fetch = originalFetch;
    vi.clearAllMocks();
  });

  describe('接口路径', () => {
    it('请求 GET /backend/api/v1/official-site/home', async () => {
      const mockHomeData: HomeData = {
        site_title: '官网标题',
        site_subtitle: '官网副标题',
        background_image: '/banner.png',
        background_blur_image: '/banner-blur.png',
        capsule_tag: { text: '新一代智能协作平台' },
        tabs: [],
        methodology: {
          display_status: true,
          main_title: '方法论',
          sub_title: '方法论说明',
          steps: [],
        },
      };

      mockFetch.mockResolvedValueOnce({
        ok: true,
        status: 200,
        json: async () => ({ code: 200, message: 'success', data: mockHomeData }),
      });

      await fetchOfficialSiteHome();

      expect(mockFetch).toHaveBeenCalledWith(
        '/backend/api/v1/official-site/home',
        expect.objectContaining({
          method: 'GET',
        })
      );
    });
  });

  describe('响应映射', () => {
    it('正确返回首页数据', async () => {
      const mockHomeData: HomeData = {
        site_title: 'AI Agent 平台',
        site_subtitle: '智能协作新体验',
        background_image: 'https://example.com/banner.png',
        background_blur_image: 'https://example.com/banner-blur.png',
        capsule_tag: { text: '热门推荐' },
        tabs: [
          {
            tab_id: 'tab-001',
            position_code: 'sales',
            position_name: '销售',
            main_title: '销售 Agent',
            sub_title: '智能销售助手',
            qrcode_url: 'https://example.com/qrcode.png',
            qrcode_status: 'available',
            agents: [
              {
                agent_id: 'agent-001',
                agent_name: 'Agent 001',
                icon_url: 'https://example.com/icon.png',
                media_url: 'https://example.com/media.png',
                media_type: 'image',
                speech_title: 'Agent 标题',
                speech_content: 'Agent 内容',
                status: 'active',
              },
            ],
          },
        ],
        methodology: {
          display_status: true,
          main_title: '方法论',
          sub_title: '方法论说明',
          steps: [
            {
              step_icon: 'https://example.com/icon.png',
              step_name: '步骤1',
              step_image: 'https://example.com/step.png',
              step_description: '步骤描述',
            },
          ],
        },
      };

      mockFetch.mockResolvedValueOnce({
        ok: true,
        status: 200,
        json: async () => ({ code: 200, message: 'success', data: mockHomeData }),
      });

      const result = await fetchOfficialSiteHome();

      expect(result).toEqual(mockHomeData);
      expect(result.tabs).toHaveLength(1);
      expect(result.tabs[0]?.agents).toHaveLength(1);
    });

    it('空 tabs 正确处理', async () => {
      const mockHomeData: HomeData = {
        site_title: '标题',
        site_subtitle: '副标题',
        background_image: null,
        background_blur_image: null,
        capsule_tag: null,
        tabs: [],
        methodology: {
          display_status: false,
          main_title: '',
          sub_title: '',
          steps: [],
        },
      };

      mockFetch.mockResolvedValueOnce({
        ok: true,
        status: 200,
        json: async () => ({ code: 200, message: 'success', data: mockHomeData }),
      });

      const result = await fetchOfficialSiteHome();

      expect(result.tabs).toHaveLength(0);
    });

    it('将后端二维码状态归一化为页面契约状态', async () => {
      const backendHomeData: BackendHomeData = {
        site_title: 'AI Agent 平台',
        site_subtitle: '智能协作新体验',
        background_image: 'https://example.com/banner.png',
        background_blur_image: 'https://example.com/banner-blur.png',
        capsule_tag: { text: '热门推荐' },
        tabs: [
          {
            tab_id: 'tab-001',
            position_code: 'sales',
            position_name: '销售',
            main_title: '销售 Agent',
            sub_title: '智能销售助手',
            qrcode_url: 'https://example.com/qrcode.png',
            qrcode_status: 'enable',
            agents: [],
          },
          {
            tab_id: 'tab-002',
            position_code: 'service',
            position_name: '客服',
            main_title: '客服 Agent',
            sub_title: '智能客服助手',
            qrcode_url: 'https://example.com/qrcode-2.png',
            qrcode_status: 'disable',
            agents: [],
          },
        ],
        methodology: {
          display_status: true,
          main_title: '方法论',
          sub_title: '方法论说明',
          steps: [],
        },
      };

      mockFetch.mockResolvedValueOnce({
        ok: true,
        status: 200,
        json: async () => ({ code: 200, message: 'success', data: backendHomeData }),
      });

      const result = await fetchOfficialSiteHome();

      expect(result.tabs[0]?.qrcode_status).toBe('available');
      expect(result.tabs[1]?.qrcode_status).toBe('unavailable');
    });
  });

  describe('失败处理', () => {
    it('业务失败抛出 ApiError', async () => {
      mockFetch.mockResolvedValueOnce({
        ok: true,
        status: 200,
        json: async () => ({ code: 400, message: '参数错误', data: null }),
      });

      await expect(fetchOfficialSiteHome()).rejects.toThrow(ApiError);
    });

    it('HTTP 失败抛出 ApiError', async () => {
      mockFetch.mockResolvedValueOnce({
        ok: false,
        status: 500,
        json: async () => ({ code: 500, message: '服务器错误', data: null }),
      });

      await expect(fetchOfficialSiteHome()).rejects.toThrow(ApiError);
    });

    it('网络失败返回 isNetworkError=true', async () => {
      mockFetch.mockRejectedValueOnce(new TypeError('Failed to fetch'));

      await expect(fetchOfficialSiteHome()).rejects.toMatchObject({
        isNetworkError: true,
      });
    });
  });
});