跳到主要内容

测试驱动开发

收藏0

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

让 AI 安装

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

mocking.md

1.4 KB查看源码

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:

// 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:

// 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

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