client.test.ts 9.74 KB
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ApiError, isApiError, createApiClient } from './client';
import axios, { type AxiosRequestConfig } from 'axios';

// Note: Tests for createApiClient request handling use axios mock
// to verify success and error response handling.

// Mock axios for request tests (只 mock default.create,保留真实的 axios)
vi.mock('axios', async () => {
  const actual = await vi.importActual<typeof axios>('axios');
  return {
    default: {
      ...actual,
      create: vi.fn(() => ({
        request: vi.fn(),
      })),
    },
  };
});

// 真实 axios 配置合并测试 - 使用真实 axios 实例验证 client.ts 的实现
describe('axios FormData 与 JSON 配置合并边界测试', () => {
  // 这些测试验证 createApiClient 在处理 FormData 和 JSON 时的正确行为
  // 注意:Node.js 测试环境中 axios 对 FormData 的处理与浏览器不同
  // 在浏览器中,axios 会自动为 FormData 生成 multipart/form-data; boundary=...
  // 在 Node.js 中,axios 默认转换为 x-www-form-urlencoded
  // 核心验证:FormData 请求不应该继承 application/json Content-Type

  it('createApiClient FormData 上传请求不继承 application/json Content-Type', async () => {
    const realAxios = await vi.importActual<typeof import('axios')>('axios');

    let capturedConfig: unknown = null;

    const axiosInstance = realAxios.default.create({
      baseURL: '/api/v1',
      timeout: 30000,
      // 不设置默认 Content-Type(模拟修复后的 client.ts)
      adapter: async (config) => {
        capturedConfig = config;
        return Promise.resolve({
          data: { code: 200, message: 'success', data: { file_url: 'https://example.com/file.png' } },
          status: 200,
          statusText: 'OK',
          headers: {},
          config,
        });
      },
    });

    const formData = new FormData();
    formData.append('file', new File(['test content'], 'test.png', { type: 'image/png' }));
    formData.append('usage_type', 'methodology_icon');

    // FormData 不设置 Content-Type(空 headers),让 axios 自动处理
    const headers = formData instanceof FormData ? {} : { 'Content-Type': 'application/json' };

    await axiosInstance.post('/official-site-upload/upload', formData, { headers });

    expect(capturedConfig).not.toBeNull();
    const config = capturedConfig as AxiosRequestConfig;
    const contentType = config.headers?.['Content-Type'] || config.headers?.['content-type'];

    // 核心验证:Content-Type 不应该是 application/json
    // 在浏览器中会是 multipart/form-data; boundary=...
    // 在 Node.js 测试环境中可能是 x-www-form-urlencoded 或 undefined
    expect(contentType).not.toBe('application/json');

    // data 应该保持为 FormData 类型(在浏览器中会保持原样)
    // 在 Node.js 中可能被转换为字符串,但不应该被 JSON.stringify
    expect(config.data instanceof FormData || typeof config.data === 'string').toBe(true);
    if (typeof config.data === 'string') {
      // Node.js 环境下转换为字符串,但不应该是 JSON 格式
      expect(config.data).not.toBe(JSON.stringify(formData));
    }
  });

  it('createApiClient JSON POST 请求正确使用 application/json', async () => {
    const realAxios = await vi.importActual<typeof import('axios')>('axios');

    let capturedConfig: unknown = null;

    const axiosInstance = realAxios.default.create({
      baseURL: '/api/v1',
      timeout: 30000,
      adapter: async (config) => {
        capturedConfig = config;
        return Promise.resolve({
          data: { code: 201, message: 'created', data: { id: 1 } },
          status: 201,
          statusText: 'Created',
          headers: {},
          config,
        });
      },
    });

    const jsonData = { name: 'test' };
    const headers = { 'Content-Type': 'application/json' };

    await axiosInstance.post('/agents', jsonData, { headers });

    expect(capturedConfig).not.toBeNull();
    const config = capturedConfig as AxiosRequestConfig;
    const contentType = config.headers?.['Content-Type'] || config.headers?.['content-type'];
    expect(contentType).toBe('application/json');
    expect(typeof config.data).toBe('string');
    expect(JSON.parse(config.data as string)).toEqual({ name: 'test' });
  });
});

describe('createApiClient request handling', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  afterEach(() => {
    vi.clearAllMocks();
  });

  it('解包 code 200 成功响应', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 200, message: 'success', data: { id: 1, name: 'test' } },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    const result = await client.get('/test');

    expect(result).toEqual({ id: 1, name: 'test' });
  });

  it('解包 code 201 创建成功响应', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 201, message: '创建成功', data: { id: 1, name: 'new' } },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    const result = await client.post('/test', { name: 'new' });

    expect(result).toEqual({ id: 1, name: 'new' });
  });

  it('非 200/201 的业务 code 抛出 ApiError', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 400, message: '参数错误', data: null },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    await expect(client.get('/test')).rejects.toThrow('参数错误');
  });

  it('code 404 抛出 ApiError', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 404, message: '资源不存在', data: null },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    await expect(client.get('/test')).rejects.toThrow('资源不存在');
  });

  it('code 409 抛出 ApiError', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 409, message: '资源冲突', data: null },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    await expect(client.post('/test', {})).rejects.toThrow('资源冲突');
  });

  it('code 500 抛出 ApiError', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 500, message: '服务器内部错误', data: null },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    await expect(client.get('/test')).rejects.toThrow('服务器内部错误');
  });

  it('code 503 抛出 ApiError', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 503, message: '外部服务不可用', data: null },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    await expect(client.get('/test')).rejects.toThrow('外部服务不可用');
  });

  it('FormData 上传不继承 JSON Content-Type,保留 multipart boundary', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 200, message: '上传成功', data: { file_url: 'https://example.com/file.png' } },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    const formData = new FormData();
    formData.append('file', new File(['test'], 'test.png', { type: 'image/png' }));
    formData.append('usage_type', 'methodology_icon');

    await client.post('/official-site-upload/upload', formData);

    const requestConfig = mockAxiosInstance.request.mock.calls[0][0];
    // FormData 请求不应该有 Content-Type: application/json
    // 应该让 axios/浏览器自动生成 multipart/form-data; boundary=...
    expect(requestConfig.headers?.['Content-Type']).not.toBe('application/json');
    // 请求体应该是原始 FormData,不是 JSON
    expect(requestConfig.data).toBe(formData);
  });

  it('JSON POST 请求保持 Content-Type: application/json', async () => {
    const mockAxiosInstance = {
      request: vi.fn().mockResolvedValueOnce({
        data: { code: 201, message: '创建成功', data: { id: 1 } },
      }),
    };
    vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);

    const client = createApiClient();
    await client.post('/agents', { name: 'test' });

    const requestConfig = mockAxiosInstance.request.mock.calls[0][0];
    expect(requestConfig.headers?.['Content-Type']).toBe('application/json');
    expect(requestConfig.data).toEqual({ name: 'test' });
  });
});

describe('isApiError', () => {
  it('识别 ApiError 实例', () => {
    const error = new ApiError('test', 400);
    expect(isApiError(error)).toBe(true);
  });

  it('非 ApiError 返回 false', () => {
    const error = new Error('test');
    expect(isApiError(error)).toBe(false);
  });

  it('null 返回 false', () => {
    expect(isApiError(null)).toBe(false);
  });

  it('undefined 返回 false', () => {
    expect(isApiError(undefined)).toBe(false);
  });
});

describe('ApiError', () => {
  it('包含正确的 message 和 code', () => {
    const error = new ApiError('参数错误', 400);
    expect(error.message).toBe('参数错误');
    expect(error.code).toBe(400);
    expect(error.name).toBe('ApiError');
  });
});