跳转到内容

Mock 使用时机

只在系统边界处使用 Mock:

  • 外部 API(支付、邮件等)
  • 数据库(有时;优先使用测试数据库)
  • 时间和随机性
  • 文件系统(有时)

不要 Mock:

  • 自己的类或模块
  • 内部协作者
  • 任何由你控制的内容

在系统边界处,设计易于 Mock 的接口:

1. 使用依赖注入

传入外部依赖,而不是在内部创建:

// Easy to mock
function processPayment(order, paymentClient) {
return paymentClient.charge(order.total);
}
// Hard to mock
function processPayment(order) {
const client = new StripeClient(process.env.STRIPE_KEY);
return client.charge(order.total);
}

2. 优先使用 SDK 风格的接口,而不是通用 fetcher

为每种外部操作创建专用函数,而不是创建一个带条件逻辑的通用函数:

// GOOD: Each function is independently mockable
const 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 mock
const api = {
fetch: (endpoint, options) => fetch(endpoint, options),
};

采用 SDK 方式意味着:

  • 每个 mock 都返回一种特定的数据结构
  • 测试设置中不需要条件逻辑
  • 更容易看出测试调用了哪些端点
  • 每个端点都有类型安全保障
英文 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 mock
function processPayment(order, paymentClient) {
return paymentClient.charge(order.total);
}
// Hard to mock
function 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 mockable
const 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 mock
const 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

鲁ICP备2025189036号