CallAssemblyDetailInputVariables.test.tsx 4.87 KB
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import CallAssemblyDetail from '../pages/Calls/CallAssemblyDetail';

const mockMessageSuccess = vi.hoisted(() => vi.fn());

/** 构建一个带模板变量和对应请求体的 mock 数据 */
function buildDetailWithVars(vars: Record<string, string>) {
  const entries = Object.entries(vars);
  const systemPrompt = entries.map(([k]) => `{{${k}}}`).join('\n');
  const userPrompt = '';
  // 请求体内容直接包含变量值(模拟真实场景)
  const content = entries.map(([, v]) => v).join('\n');
  return {
    id: '1',
    request_body: { model: 'gpt-4', messages: [{ role: 'user', content }] },
    template_id: 'tpl-1',
    template_info: {
      id: 1,
      title: '测试模板',
      code: 'test',
      template_type: 'text_generation',
      version: 1,
      system_prompt: systemPrompt,
      user_prompt: userPrompt,
    },
    provider_name: 'OpenAI',
    account_name: '主账号',
    sensitive_replacements: null,
    response_body: { choices: [{ message: { content: 'ok' } }] },
    status: 'success',
    prompt_tokens: 10,
    completion_tokens: 20,
    total_tokens: 30,
    duration_ms: 500,
    created_at: '2026-06-25T12:00:00',
    called_at: '2026-06-25T12:00:00',
    model_name: 'gpt-4',
    biz_type: null,
    error_message: null,
  };
}

const mockNoTemplateDetail = vi.hoisted(() => ({
  id: '2',
  request_body: { model: 'gpt-4', messages: [{ role: 'user', content: '你好' }] },
  template_id: null,
  template_info: null,
  provider_name: 'OpenAI',
  account_name: '主账号',
  sensitive_replacements: null,
  response_body: { choices: [{ message: { content: '你好!' } }] },
  status: 'success',
  prompt_tokens: 10,
  completion_tokens: 20,
  total_tokens: 30,
  duration_ms: 500,
  created_at: '2026-06-25T12:00:00',
  called_at: '2026-06-25T12:00:00',
  model_name: 'gpt-4',
  biz_type: null,
  error_message: null,
}));

let mockDetail: any = null;

vi.mock('../stores/callRecordStore', () => ({
  useCallRecordStore: () => ({
    detail: mockDetail,
    detailLoading: false,
    getCallDetail: vi.fn(),
  }),
}));

vi.mock('antd', async () => {
  const actual = await vi.importActual('antd');
  return {
    ...actual,
    message: {
      success: mockMessageSuccess,
      error: vi.fn(),
    },
  };
});

describe('CallAssemblyDetail — 输入变量展示与复制', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    Object.assign(navigator, {
      clipboard: {
        writeText: vi.fn().mockResolvedValue(undefined),
      },
    });
  });

  it('有模板变量时渲染变量卡片', async () => {
    mockDetail = buildDetailWithVars({ question: '你好世界', language: '中文' });

    render(<CallAssemblyDetail open={true} callId="1" onClose={() => {}} />);

    await waitFor(() => {
      expect(screen.getByText('输入变量')).toBeInTheDocument();
    });

    // 检查变量卡片元素
    const cards = document.querySelectorAll('.variable-card');
    expect(cards.length).toBe(2);

    // 检查变量值
    const values = document.querySelectorAll('.variable-card-value');
    expect(values[0].textContent).toBe('你好世界');
    expect(values[1].textContent).toBe('中文');
  });

  it('点击变量复制按钮复制变量值', async () => {
    mockDetail = buildDetailWithVars({ question: '你好世界' });

    render(<CallAssemblyDetail open={true} callId="1" onClose={() => {}} />);

    await waitFor(() => {
      expect(screen.getByText('输入变量')).toBeInTheDocument();
    });

    // 找到变量卡片上的复制按钮
    const copyBtns = document.querySelectorAll('.variable-copy-btn');
    expect(copyBtns.length).toBe(1);
    fireEvent.click(copyBtns[0]);

    await waitFor(() => {
      expect(navigator.clipboard.writeText).toHaveBeenCalledWith('你好世界');
    });
    await waitFor(() => {
      expect(mockMessageSuccess).toHaveBeenCalledWith('已复制');
    });
  });

  it('无模板时不显示输入变量区域', async () => {
    mockDetail = mockNoTemplateDetail;

    render(<CallAssemblyDetail open={true} callId="2" onClose={() => {}} />);

    await waitFor(() => {
      expect(screen.getByText('最终请求体')).toBeInTheDocument();
    });

    expect(screen.queryByText('输入变量')).not.toBeInTheDocument();
  });

  it('点击请求体复制按钮复制完整请求 JSON', async () => {
    mockDetail = buildDetailWithVars({ question: '你好' });

    render(<CallAssemblyDetail open={true} callId="1" onClose={() => {}} />);

    await waitFor(() => {
      const copyBtn = screen.getByTitle('复制请求体');
      fireEvent.click(copyBtn);
    });

    const expectedJson = JSON.stringify(mockDetail.request_body, null, 2);
    expect(navigator.clipboard.writeText).toHaveBeenCalledWith(expectedJson);
    expect(mockMessageSuccess).toHaveBeenCalledWith('请求体已复制');
  });
});