跳到主要内容

测试驱动开发

收藏0

红绿重构循环的实战规范:什么算好测试、测试该写在哪个接口缝、三个反模式与循环法则,含 mock 与测试写法两篇参考。

让 AI 安装

星光尘缘最新版本 0.1.0更新于 2026-11-09下载 0 次

mocking.md

1.4 KB查看排版效果
1# When to Mock
2
3Mock at **system boundaries** only:
4
5- External APIs (payment, email, etc.)
6- Databases (sometimes - prefer test DB)
7- Time/randomness
8- File system (sometimes)
9
10Don't mock:
11
12- Your own classes/modules
13- Internal collaborators
14- Anything you control
15
16## Designing for Mockability
17
18At system boundaries, design interfaces that are easy to mock:
19
20**1. Use dependency injection**
21
22Pass external dependencies in rather than creating them internally:
23
24```typescript
25// Easy to mock
26function processPayment(order, paymentClient) {
27 return paymentClient.charge(order.total);
28}
29
30// Hard to mock
31function processPayment(order) {
32 const client = new StripeClient(process.env.STRIPE_KEY);
33 return client.charge(order.total);
34}
35```
36
37**2. Prefer SDK-style interfaces over generic fetchers**
38
39Create specific functions for each external operation instead of one generic function with conditional logic:
40
41```typescript
42// GOOD: Each function is independently mockable
43const api = {
44 getUser: (id) => fetch(`/users/${id}`),
45 getOrders: (userId) => fetch(`/users/${userId}/orders`),
46 createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),
47};
48
49// BAD: Mocking requires conditional logic inside the mock
50const api = {
51 fetch: (endpoint, options) => fetch(endpoint, options),
52};
53```
54
55The SDK approach means:
56- Each mock returns one specific shape
57- No conditional logic in test setup
58- Easier to see which endpoints a test exercises
59- Type safety per endpoint

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。