# 智能体测试指南

## 环境配置

### 1. 依赖安装
```bash
# 安装所需依赖
pnpm install

# 开发依赖
- jest: 测试框架
- ts-jest: TypeScript 支持
- msw: API 模拟
- @faker-js/faker: 测试数据生成
```

### 2. 配置文件
- `jest.config.agent.js`: Jest 测试配置
- `tests/setup.agent.ts`: 测试环境初始化
- `tests/__fixtures__/handlers.ts`: API 模拟处理器

## 测试用例编写规范

### 1. 文件命名
- 单智能体测试：`*.agent.test.ts`
- 性能测试：`*.perf.test.ts`
- 集成测试：`*.integration.test.ts`

### 2. 目录结构
```
tests/
├── agents/              # 智能体测试
│   ├── single/         # 单智能体测试
│   ├── collaboration/  # 多智能体协作测试
│   └── integration/   # 集成测试
├── __fixtures__/       # 测试数据和模拟
└── utils/             # 测试工具
```

### 3. 测试用例组织
```typescript
describe('测试组名称', () => {
  // 测试前准备
  beforeEach(() => {
    // 初始化测试对象
  });

  // 测试后清理
  afterEach(() => {
    // 清理资源
  });

  describe('功能分组', () => {
    it('应该完成特定功能', async () => {
      // 准备测试数据
      // 执行测试
      // 验证结果
    });
  });
});
```

### 4. 最佳实践
- 每个测试用例只测试一个功能点
- 使用清晰的测试描述
- 合理使用 `beforeEach` 和 `afterEach`
- 及时清理资源
- 使用 `jest.useFakeTimers()` 控制时间相关测试

## 测试场景

### 1. 基础功能测试
- 初始化测试
- 消息处理测试
- 状态管理测试

### 2. 错误处理测试
- 输入验证
- 并发处理
- 超时处理
- 错误恢复

### 3. 性能测试
- 响应时间测试
- 内存使用测试
- 并发性能测试

## 常见问题和解决方案

### 1. 异步测试
```typescript
// 正确的异步测试写法
it('异步测试', async () => {
  const response = await agent.process({
    type: 'command',
    content: '测试'
  });
  expect(response.type).toBe('response');
});
```

### 2. 定时器测试
```typescript
// 使用 Jest 的假定时器
jest.useFakeTimers();
const promise = agent.process({ type: 'command', content: '测试' });
jest.advanceTimersByTime(1000);
const result = await promise;
jest.useRealTimers();
```

### 3. 并发测试
```typescript
// 并发请求测试
const requests = Array(5).fill(null).map(() => agent.process({
  type: 'command',
  content: '并发测试'
}));
const responses = await Promise.all(requests);
```

### 4. 资源清理
```typescript
afterEach(() => {
  // 清理定时器
  jest.useRealTimers();
  // 清理智能体资源
  agent.destroy();
});
```

## 测试覆盖率要求

- 分支覆盖率：80%
- 函数覆盖率：80%
- 行覆盖率：80%
- 语句覆盖率：80%

## 调试技巧

### 1. 使用 Jest CLI 选项
```bash
# 运行特定测试
npx jest -c jest.config.agent.js path/to/test

# 监视模式
npx jest -c jest.config.agent.js --watch

# 显示详细日志
npx jest -c jest.config.agent.js --verbose
```

### 2. 使用 VS Code 调试
1. 设置断点
2. 使用 VS Code 的 Jest 插件
3. 使用调试控制台查看变量

## 持续集成

- 在提交代码前运行测试
- 确保所有测试通过
- 保持测试覆盖率达标
- 定期进行性能测试 