此技能提供即用型 Jest 测试模式,包括工厂函数、自定义渲染工具和模拟策略,帮助开发者遵循 TDD 原则编写可维护、DRY 的测试。
下载技能 ZIP
在 Claude 中上传
前往 设置 → 功能 → 技能 → 上传技能
开启并开始使用
测试它
正在使用“testing-patterns”。 创建一个用户数据的工厂函数
预期结果:
```typescript
interface User {
id: string;
name: string;
email: string;
role: 'admin' | 'user';
}
const getMockUser = (overrides?: Partial<User>): User => ({
id: '123',
name: 'John Doe',
email: 'john@example.com',
role: 'user',
...overrides,
});
```
正在使用“testing-patterns”。 向我展示自定义渲染函数
预期结果:
```typescript
export const renderWithTheme = (ui: React.ReactElement) => {
return render(
<ThemeProvider>{ui}</ThemeProvider>
);
};
```
正在使用“testing-patterns”。 我应该如何组织我的测试?
预期结果:
Use describe blocks to group related tests: describe('ComponentName', () => { describe('Rendering', () => {...}); describe('User interactions', () => {...}); describe('Edge cases', () => {...}); });
安全审计
安全Security review completed. All 42 static findings are false positives triggered by the static analyzer misinterpreting: (1) markdown code formatting backticks as shell commands, (2) TypeScript generics like Partial<X> as cryptographic patterns, and (3) the word 'APIs' as network reconnaissance. The skill is legitimate Jest testing documentation with no security concerns.
质量评分
你能构建什么
设置测试基础设施
创建自定义渲染函数和工厂工具,用 ThemeProvider 等必需提供者包装组件,减少每个测试中的样板代码。
编写可维护的单元测试
使用工厂函数生成一致的测试数据,使测试更易于阅读、维护,并在数据结构变化时易于更新。
遵循 TDD 方法论
应用红 - 绿 - 重构周期,先编写失败的测试,然后实现最少代码使其通过,确保测试驱动开发。
试试这些提示
Help me set up a basic test file for a React component. Show me how to create a custom render function that wraps the component with a ThemeProvider.
Create a factory function called getMockUser that returns a user object with default values for id, name, email, and role. Show how to override specific properties using Partial type.
Show me how to mock a module like 'utils/analytics' in Jest. Include how to access the mock in the test and how to mock return values.
Walk me through the TDD workflow for adding a new feature. Start with writing a failing test, then show the minimal implementation to pass it.
最佳实践
- 始终使用工厂函数处理 props 和数据,保持测试 DRY 和一致
- 通过公共 API 测试行为,而非实现细节
- 使用描述性的测试名称,解释正在测试的行为
避免
- 避免测试模拟行为而非实际组件行为
- 不要在测试中重复测试数据——改用工厂函数
- 避免测试可能在重构中变化的实现细节