Unit, integration, and E2E testing patterns with framework-specific guidance. Use when asked to "write tests", "add test coverage", "testing strategy", "test this function", "create test suite", "fix flaky tests", or "improve test quality".
数据来源:ClawHub。 在 ClawSkills 查看
选择你使用的 Agent
方法一:命令行安装(推荐)
推荐(无需提前安装 clawhub)
npx clawhub@latest --dir ~/.claude/skills install testing-patterns或使用 clawhub CLI(需提前安装)
clawhub --dir ~/.claude/skills install testing-patterns⚠️ 需要 Node.js 18+,没有 Node?请使用下方方法二直接下载 ZIP。 安装 Node.js →
方法二:手动下载安装(无需 Node)
下载 ZIP,解压后将文件夹放到以下路径,重启 Agent 即可:
安装路径
~/.claude/skills/testing-patterns/💡解压后将文件夹放到上方路径,重启 Agent 即可生效
--- name: testing-patterns model: standard category: testing description: Unit, integration, and E2E testing patterns with framework-specific guidance. Use when asked to "write tests", "add test coverage", "testing strategy", "test this function", "create test suite", "fix flaky tests", or "improve test quality". version: 1.0 ---
> Write tests that catch bugs, not tests that pass. — Confidence through coverage, speed through isolation.
---
| Level | Ratio | Speed | Cost | Confidence | Scope | |-------|-------|-------|------|------------|-------| | Unit | ~70% | ms | Low | Low (isolated) | Single function/class | | Integration | ~20% | seconds | Medium | Medium | Module boundaries, APIs, DB | | E2E | ~10% | minutes | High | High (realistic) | Full user workflows |
> Rule: If your E2E tests outnumber your unit tests, invert the pyramid.
---
| Pattern | When to Use | Structure | |---------|------------|-----------| | Arrange-Act-Assert | Default for all unit tests | Setup, Execute, Verify | | Given-When-Then | BDD-style, behavior-focused | Precondition, Action, Outcome | | Parameterized | Same logic, multiple inputs | Data-driven test cases | | Snapshot | UI components, serialized output | Compare against saved baseline | | Property-Based | Mathematical invariants | Generate random inputs, assert properties |
The default structure for every unit test. Clear separation of setup, execution, and verification makes tests readable and maintainable.
// Clean AAA structure
test('calculates order total with tax', () => {
// Arrange
const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }];
const taxRate = 0.08;
// Act
const total = calculateTotal(items, taxRate);
// Assert
expect(total).toBe(27.0);
});
Use the right type of test double for the situation. Each serves a different purpose.
| Double | Purpose | When to Use | Example | |--------|---------|-------------|---------| | Stub | Returns canned data | Control indirect input | jest.fn().mockReturnValue(42) | | Mock | Verifies interactions | Assert something was called | expect(mock).toHaveBeenCalledWith('arg') | | Spy | Wraps real implementation | Observe without replacing | jest.spyOn(service, 'save') | | Fake | Working simplified impl | Need realistic behavior | In-memory database, fake HTTP server |
// Stub — control indirect input
const getUser = jest.fn().mockResolvedValue({ id: 1, name: 'Alice' });
// Spy — observe without replacing
const spy = jest.spyOn(logger, 'warn');
processInvalidInput(data);
expect(spy).toHaveBeenCalledWith('Invalid input received');
// Fake — lightweight substitute
class FakeUserRepo implements UserRepository {
private users = new Map<string, User>();
async save(user: User) { this.users.set(user.id, user); }
async findById(id: string) { return this.users.get(id) ?? null; }
}
Use parameterized tests when the same logic needs verification with multiple inputs. This eliminates copy-paste tests while providing comprehensive coverage.
// Vitest/Jest
test.each([
['hello', 'HELLO'],
['world', 'WORLD'],
['', ''],
['123abc', '123ABC'],
])('toUpperCase(%s) returns %s', (input, expected) => {
expect(input.toUpperCase()).toBe(expected);
});
# pytest
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("world", "WORLD"),
("", ""),
])
def test_to_upper(input, expected):
assert input.upper() == expected
// Go — table-driven tests (idiomatic)
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive", 2, 3, 5},
{"zero", 0, 0, 0},
{"negative", -1, -2, -3},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := Add(tc.a, tc.b); got != tc.expected {
t.Errorf("Add(%d,%d) = %d, want %d", tc.a, tc.b, got, tc.expected)
}
})
}
}
---
| Strategy | Approach | Trade-off | |----------|----------|-----------| | Transaction rollback | Wrap each test in a transaction, rollback after | Fast, but hides commit bugs | | Fixtures/seeds | Load known data before suite | Predictable, but brittle if schema changes | | Factory functions | Generate data programmatically | Flexible, but more setup code | | Testcontainers | Spin up real DB in Docker | Realistic, but slower startup |
// Transaction rollback pattern (Prisma)
beforeEach(async () => {
await prisma.$executeRaw`BEGIN`;
});
afterEach(async () => {
await prisma.$executeRaw`ROLLBACK`;
});
test('creates user in database', async () => {
const user = await createUser({ name: 'Alice', email: '[email protected]' });
const found = await prisma.user.findUnique({ where: { id: user.id } });
expect(found?.name).toBe('Alice');
});
// Supertest (Node.js)
import request from 'supertest';
import { app } from '../src/app';
describe('POST /api/users', () => {
it('creates a user and returns 201', async () => {
const res = await request(app)
.post('/api/users')
.send({ name: 'Alice', email: '[email protected]' })
.expect(201);
expect(res.body).toMatchObject({
id: expect.any(String),
name: 'Alice',
});
});
it('returns 400 for invalid email', async () => {
await request(app)
.post('/api/users')
.send({ name: 'Alice', email: 'not-an-email' })
.expect(400);
});
});
---
The fundamental rule: mock at system boundaries (external APIs, databases, file systems) and never mock internal domain logic.
// BAD — mocking internal implementation
jest.mock('./utils/formatDate'); // Breaks on refactor
// GOOD — mocking external boundary
jest.mock('./services/paymentGateway'); // Third-party API is the boundary
| Mock | Don't Mock | |------|-----------| | HTTP APIs, external services | Pure functions | | Database (in unit tests) | Your own domain logic | | File system, network | Data transformations | | Time/Date (Date.now) | Simple calculations | | Environment variables | Internal class methods |
Structure code so dependencies can be swapped in tests. This is the single most impactful pattern for testable code.
// Injectable dependencies — easy to test
class OrderService {
constructor(
private paymentGateway: PaymentGateway,
private inventory: InventoryService,
private notifier: NotificationService,
) {}
async placeOrder(order: Order): Promise<OrderResult> {
const stock = await this.inventory.check(order.items);
if (!stock.available) return { status: 'out_of_stock' };
const payment = await this.paymentGateway.charge(order.total);
if (!payment.success) return { status: 'payment_failed' };
await this.notifier.send(order.userId, 'Order confirmed');
return { status: 'confirmed', id: payment.transactionId };
}
}
// In tests — inject fakes
const service = new OrderService(
new FakePaymentGateway(),
new FakeInventory({ available: true }),
new FakeNotifier(),
);
---
...
安装 Testing Patterns 后,可以对 AI 说这些话来触发它
Help me get started with Testing Patterns
Explains what Testing Patterns does, walks through the setup, and runs a quick demo based on your current project
Use Testing Patterns to unit, integration, and E2E testing patterns with framework-specific...
Invokes Testing Patterns with the right parameters and returns the result directly in the conversation
What can I do with Testing Patterns in my developer & devops workflow?
Lists the top use cases for Testing Patterns, with example commands for each scenario
将技能文件夹放到 ~/.claude/skills/testing-patterns/ 目录(个人级,所有项目可用),或 .claude/skills/testing-patterns/(项目级)。重启 AI 客户端后,用 /testing-patterns 主动调用,或让 AI 根据上下文自动发现并使用。
Testing Patterns 支持 Claude、Cursor、OpenClaw,可与这些 AI 平台无缝集成,扩展其能力。
Testing Patterns 可免费安装使用。请查阅仓库了解许可证信息。
Unit, integration, and E2E testing patterns with framework-specific guidance. Use when asked to "write tests", "add test coverage", "testing strategy", "test this function", "create test suite", "fix flaky tests", or "improve test quality".
Testing Patterns 属于「Developer & DevOps」分类,该分类的技能帮助 AI 智能体在此领域执行专业任务。
Automate my developer & devops tasks using Testing Patterns
Identifies repetitive steps in your workflow and sets up Testing Patterns to handle them automatically