name: 测试生成 description: 生成全面测试,遵循项目测试模式。在实现功能后使用。
测试生成技能
目的
创建一致、全面的测试。
测试模式
单元测试模式
describe('[单元测试对象]', () => {
describe('[方法/函数]', () => {
it('应该 [预期行为] 当 [条件]', () => {
// 安排
const input = ...;
const expected = ...;
// 执行
const result = functionUnderTest(input);
// 断言
expect(result).toEqual(expected);
});
it('应该抛出 [错误] 当 [无效条件]', () => {
// 安排
const invalidInput = ...;
// 执行与断言
expect(() => functionUnderTest(invalidInput))
.toThrow(ExpectedError);
});
});
});
集成测试模式
参考: patterns/integration-tests.md
E2E测试模式
覆盖率目标
| 类型 | 行数 | 函数数 | 分支数 |
|---|---|---|---|
| 单元测试 | 80% | 80% | 70% |
| 集成测试 | 60% | 60% | 50% |
| E2E测试 | 关键路径 | - | - |
测试命名约定
[应该/是否] [预期行为] [当/给定] [条件]
示例:
应该返回用户 当有效ID提供时应该抛出NotFoundError 当用户不存在时应该禁用按钮 当表单无效时
需要测试的内容
- 成功路径(正常操作)
- 边界情况(极限条件)
- 错误情况(异常)
- 状态转换
测试结构
AAA模式
// 安排 - 设置测试数据和条件
const input = createTestInput();
const mockService = createMock();
// 执行 - 执行测试代码
const result = await functionUnderTest(input);
// 断言 - 验证结果
expect(result).toEqual(expectedOutput);
expect(mockService.method).toHaveBeenCalledWith(expectedArgs);
BDD风格
describe('用户服务', () => {
describe('当创建用户时', () => {
it('应该将用户保存到数据库', () => { });
it('应该发送欢迎邮件', () => { });
it('应该返回创建的用户', () => { });
});
describe('当邮件无效时', () => {
it('应该抛出ValidationError', () => { });
});
});
测试模板
使用: templates/test-template.ts
最佳实践
要做的事
- 测试行为,而非实现
- 使用描述性测试名称
- 保持测试独立性
- 使用工厂方法生成测试数据
- 模拟外部依赖
不要做的事
- 直接测试私有方法
- 在测试间共享状态
- 在测试中使用生产数据
- 过度模拟(测试应有意义)
- 编写不稳定测试
存储位置
保存测试报告到: docs/reviews/test-report-{session}.md