Mock 使用时机
什么时候使用 Mock
Section titled “什么时候使用 Mock”只在系统边界处使用 Mock:
- 外部 API(支付、邮件等)
- 数据库(有时;优先使用测试数据库)
- 时间和随机性
- 文件系统(有时)
不要 Mock:
- 自己的类或模块
- 内部协作者
- 任何由你控制的内容
为 Mock 设计
Section titled “为 Mock 设计”在系统边界处,设计易于 Mock 的接口:
1. 使用依赖注入
传入外部依赖,而不是在内部创建:
// Easy to mockfunction processPayment(order, paymentClient) { return paymentClient.charge(order.total);}
// Hard to mockfunction processPayment(order) { const client = new StripeClient(process.env.STRIPE_KEY); return client.charge(order.total);}2. 优先使用 SDK 风格的接口,而不是通用 fetcher
为每种外部操作创建专用函数,而不是创建一个带条件逻辑的通用函数:
// GOOD: Each function is independently mockableconst api = { getUser: (id) => fetch(`/users/${id}`), getOrders: (userId) => fetch(`/users/${userId}/orders`), createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),};
// BAD: Mocking requires conditional logic inside the mockconst api = { fetch: (endpoint, options) => fetch(endpoint, options),};采用 SDK 方式意味着:
- 每个 mock 都返回一种特定的数据结构
- 测试设置中不需要条件逻辑
- 更容易看出测试调用了哪些端点
- 每个端点都有类型安全保障
原文链接和 commit
Section titled “原文链接和 commit”- 技能页 tdd
- 文件
skills/engineering/tdd/mocking.md - 提交
d81f3a1
英文 mocking.md
# When to Mock
Mock at **system boundaries** only:
- External APIs (payment, email, etc.)- Databases (sometimes - prefer test DB)- Time/randomness- File system (sometimes)
Don't mock:
- Your own classes/modules- Internal collaborators- Anything you control
## Designing for Mockability
At system boundaries, design interfaces that are easy to mock:
**1. Use dependency injection**
Pass external dependencies in rather than creating them internally:
```typescript// Easy to mockfunction processPayment(order, paymentClient) { return paymentClient.charge(order.total);}
// Hard to mockfunction processPayment(order) { const client = new StripeClient(process.env.STRIPE_KEY); return client.charge(order.total);}```
**2. Prefer SDK-style interfaces over generic fetchers**
Create specific functions for each external operation instead of one generic function with conditional logic:
```typescript// GOOD: Each function is independently mockableconst api = { getUser: (id) => fetch(`/users/${id}`), getOrders: (userId) => fetch(`/users/${userId}/orders`), createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),};
// BAD: Mocking requires conditional logic inside the mockconst api = { fetch: (endpoint, options) => fetch(endpoint, options),};```
The SDK approach means:- Each mock returns one specific shape- No conditional logic in test setup- Easier to see which endpoints a test exercises- Type safety per endpoint非官方学习站,与 Matt Pocock 和 AI Hero 没有隶属关系。本站不提供可安装的中文技能包。
技能原文采用 MIT 许可。Copyright (c) 2026 Matt Pocock