Mock at system boundaries only:
只在系統邊界模擬:
Don't mock:
不要模擬:
At system boundaries, design interfaces that are easy to mock:
在系統邊界,設計容易模擬的介面:
1. Use dependency injection
1. 使用依賴注入
Pass external dependencies in rather than creating them internally:
把外部相依傳入,而不是在內部建立:
// 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);
}
// 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
2. 偏好 SDK 風格的介面,而不是通用 fetcher
Create specific functions for each external operation instead of one generic function with conditional logic:
為每個外部操作建立特定函式,而不是一個帶條件邏輯的通用函式:
// 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),
};
// 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
SDK 方式的好處: - 每個 mock 回傳一個特定形狀 - 測試設定中沒有條件邏輯 - 更容易看出一個測試觸及哪些端點 - 每個端點都有型別安全