# mm 单元测试与调试指南

## 规则（Rules）

- 使用 Jest 测试框架，测试文件以 `.test.js` 或 `.spec.js` 结尾
- 测试文件放在项目根目录或 `__tests__/` 目录下
- 测试应模拟 `ctx` 和 `db` 上下文，避免依赖真实服务

## 方法（Methods）

### 步骤1：安装 Jest

```bash
npm install --save-dev jest
```

### 步骤2：配置 package.json

```json
"scripts": {
    "test": "jest",
    "test:watch": "jest --watch"
}
```

### 步骤3：编写测试用例

```javascript
describe('用户API', () => {
    // 模拟 ctx 上下文
    const mockCtx = {
        request: { query: { id: 1 }, body: {} }
    };

    // 模拟 db 数据管理器
    const mockDb = {
        new: function(table, key) {
            return {
                get: async (cond) => [{ id: 1, name: '测试' }],
                getObj: async (cond) => ({ id: 1, name: '测试' })
            };
        }
    };

    it('应返回用户信息', async () => {
        var handler = require('./app/user/plugin/main/api_user_client/info/index.js');
        var result = await handler.main(mockCtx, mockDb);
        expect(result.success).toBe(true);
    });
});
```

### 步骤4：运行测试

```bash
npm test
```

## 技巧（Tips）

- 模拟 `db.new()` 返回假数据，避免连接真实数据库
- 使用 Jest 的 `mockImplementation` 模拟复杂方法
- 测试后清理生成的临时文件和数据
- API handler 的 `main(ctx, db)` 函数签名固定，方便模拟
