Token导航 LogoToken导航

Agent Skill · 研究检索

testing-patterns(测试模式)

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

testing-patterns 是研究检索类 Agent Skill,可用宿主为 OpenClaw,通过ClawHub获取,权限为接触敏感数据;许可证为 MIT-0,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 1,017。

总安装 129,975周安装 5,362GitHub Stars 2下载 42,467核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT-0
版本
0.1.0

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:testing-patterns(测试模式)
来源仓库:https://github.com/wpank/testing-patterns
安装命令:
openclaw skills install testing-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 OpenClaw 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

ClawHubOpenClaw
openclaw skills install testing-patterns

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

具有特定于框架的指导的单元、集成和 E2E 测试模式。当被要求“编写测试”、“添加测试覆盖率”、“测试策略”、“测试此功能”、“创建测试套件”、“修复片状测试”或“提高测试质量”时使用。

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 OpenClaw;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 openclaw skills install testing-patterns;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

testing-patterns 怎么安装?

在终端执行 openclaw skills install testing-patterns。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

testing-patterns 支持哪些 AI 工具?

公开资料标注支持 OpenClaw。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

testing-patterns 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

testing-patterns 是免费的吗?

来源标注的许可证是 MIT-0。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

testing-patterns 用的人多吗?

公开数据是累计安装 129,975 次,近一周安装 5,362 次,下载 42,467 次,GitHub 2 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

testing-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 专注 OpenClaw 一种宿主,触发方式和使用习惯不用来回切换。
  • 许可证明确为 MIT-0,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 OpenClaw,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
testing-patterns

测试模式 · 本页

129,9752接触敏感数据MIT-0通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

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

Testing Patterns

Write tests that catch bugs, not tests that pass. — Confidence through coverage, speed through isolation.

Testing Pyramid

LevelRatioSpeedCostConfidenceScope
Unit~70%msLowLow (isolated)Single function/class
Integration~20%secondsMediumMediumModule boundaries, APIs, DB
E2E~10%minutesHighHigh (realistic)Full user workflows
Rule: If your E2E tests outnumber your unit tests, invert the pyramid.

Unit Testing Patterns

Core Patterns

PatternWhen to UseStructure
Arrange-Act-AssertDefault for all unit testsSetup, Execute, Verify
Given-When-ThenBDD-style, behavior-focusedPrecondition, Action, Outcome
ParameterizedSame logic, multiple inputsData-driven test cases
SnapshotUI components, serialized outputCompare against saved baseline
Property-BasedMathematical invariantsGenerate random inputs, assert properties

Arrange-Act-Assert (AAA)

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);
});

Test Doubles

Use the right type of test double for the situation. Each serves a different purpose.

DoublePurposeWhen to UseExample
StubReturns canned dataControl indirect inputjest.fn().mockReturnValue(42)
MockVerifies interactionsAssert something was calledexpect(mock).toHaveBeenCalledWith('arg')
SpyWraps real implementationObserve without replacingjest.spyOn(service, 'save')
FakeWorking simplified implNeed realistic behaviorIn-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; }
}

Parameterized Tests

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)
            }
        })
    }
}

Integration Testing Patterns

Database Testing Strategies

StrategyApproachTrade-off
Transaction rollbackWrap each test in a transaction, rollback afterFast, but hides commit bugs
Fixtures/seedsLoad known data before suitePredictable, but brittle if schema changes
Factory functionsGenerate data programmaticallyFlexible, but more setup code
TestcontainersSpin up real DB in DockerRealistic, 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: 'a@b.com' });
  const found = await prisma.user.findUnique({ where: { id: user.id } });
  expect(found?.name).toBe('Alice');
});

API Testing

// 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: 'alice@test.com' })
      .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);
  });
});

Mocking Best Practices

Mock Boundaries, Not Implementations

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

When to Mock vs Not Mock

MockDon't Mock
HTTP APIs, external servicesPure functions
Database (in unit tests)Your own domain logic
File system, networkData transformations
Time/Date (Date.now)Simple calculations
Environment variablesInternal class methods

Dependency Injection for Testability

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(),
);

Framework Quick Reference

FrameworkLanguageTypeTest RunnerAssertion
JestJS/TSUnit/IntegrationBuilt-inexpect()
VitestJS/TSUnit/IntegrationVite-nativeexpect() (Jest-compatible)
PlaywrightJS/TS/PythonE2EBuilt-inexpect() / locators
CypressJS/TSE2EBuilt-incy.should()
pytestPythonUnit/IntegrationBuilt-inassert
Go testingGoUnit/Integrationgo testt.Error() / testify
RustRustUnit/Integrationcargo testassert!() / assert_eq!()
JUnit 5Java/KotlinUnit/IntegrationBuilt-inassertEquals()
RSpecRubyUnit/IntegrationBuilt-inexpect().to
PHPUnitPHPUnit/IntegrationBuilt-in$this->assert*()
xUnitC#Unit/IntegrationBuilt-inAssert.Equal()

Test Quality Checklist

QualityRuleWhy
DeterministicSame input produces same result, every timeFlaky tests erode trust
IsolatedNo shared mutable state between testsOrder-dependent tests break in CI
FastUnit: < 10ms, Integration: < 1s, E2E: < 30sSlow tests don't get run
ReadableTest name describes the scenario and expectationTests are documentation
MaintainableChange one behavior, change one testBrittle tests slow development
FocusedOne logical assertion per testFailures pinpoint the problem
Naming convention: test_[unit]_[scenario]_[expected result] or should [do X] when [condition Y]

Coverage Strategy

When to Aim for What

TargetWhenRationale
80%+ line coverageBusiness logic, utilities, core domainHigh ROI — catches most regressions
90%+ branch coveragePayment processing, auth, security-criticalEdge cases matter here
100% coverageAlmost never — diminishing returnsGetter/setter tests add noise, not confidence
Mutation testingCritical paths after coverage is highVerifies tests actually catch bugs

What NOT to Test

SkipReason
Generated code (Prisma client, protobuf)Maintained by tooling
Third-party library internalsNot your responsibility
Simple getters/settersNo logic to verify
Configuration filesTest the behavior they configure instead
Console.log / print statementsSide effects with no business value

Test Organization

src/
├── services/
│   ├── order.service.ts
│   └── order.service.test.ts      # Co-located unit tests
├── api/
│   └── routes/
│       └── orders.ts
tests/
├── integration/
│   ├── api/
│   │   └── orders.test.ts         # API integration tests
│   └── db/
│       └── order.repo.test.ts     # DB integration tests
├── e2e/
│   ├── pages/                     # Page objects
│   │   └── checkout.page.ts
│   └── specs/
│       └── checkout.spec.ts       # E2E specs
└── helpers/
    ├── factories.ts               # Test data factories
    └── setup.ts                   # Global test setup
Rule: Co-locate unit tests with source. Separate integration and E2E tests into dedicated directories.

Anti-Patterns

Anti-PatternProblemFix
Testing implementationTests break on refactor, not on bugsTest behavior and outputs, not internals
Flaky testsNon-deterministic failures erode CI trustRemove time/order/network dependencies
Test pollutionShared mutable state leaks between testsReset state in beforeEach / setUp
Sleeping in testssleep(2000) is slow and unreliableUse explicit waits, polling, or events
Giant arrange50 lines of setup obscure intentExtract factories/builders/fixtures
Assert-free testsTest runs but verifies nothingEvery test must assert or expect
OvermockingMocking everything tests nothing realOnly mock external boundaries
Copy-paste testsDuplicated tests diverge and rotUse parameterized tests or helpers
Testing the frameworkVerifying library code worksTest *your* logic, trust dependencies
Ignoring test failuresskip, xit, @Disabled accumulateFix or delete — never hoard skipped tests
Tight coupling to DBTests fail when schema changesUse repository pattern + fakes for unit tests
One giant testSingle test covers 10 scenariosSplit into focused, named tests
No test for bug fixRegression reappears laterEvery bug fix gets a regression test

NEVER Do

  1. NEVER test implementation details instead of behavior — tests must verify what the code does, not how it does it
  2. NEVER use sleep() in tests — use explicit waits, polling, events, or assertions that auto-retry
  3. NEVER share mutable state between tests — each test sets up and tears down its own state
  4. NEVER write assert-free tests — a test that asserts nothing proves nothing
  5. NEVER mock internal domain logic — only mock at system boundaries (network, DB, filesystem, clock)
  6. NEVER skip tests without a linked issue and a plan to re-enable — skipped tests rot into permanent gaps
  7. NEVER leave a test suite in a failing state — fix it or remove it with justification before moving on
  8. NEVER chase 100% coverage as a goal — coverage percentage is a tool, not a target; strong assertions on critical paths beat weak assertions everywhere

Summary

DoDon't
Test behavior, not implementationMock everything in sight
Write the test before fixing a bugSkip tests to ship faster
Keep tests fast and deterministicUse sleep() or shared state
Use factories for test dataCopy-paste setup across tests
Mock at system boundariesMock internal functions
Name tests descriptivelyName tests test1, test2
Run tests in CI on every pushOnly run tests locally
Delete or fix skipped testsLet @skip accumulate forever
Use parameterized tests for variantsDuplicate test code
Inject dependencies for testabilityHard-code dependencies
Remember: Tests are a safety net — a fast, trustworthy suite lets you refactor fearlessly and ship with confidence.

平台分布

OpenClaw

90.88%
按下载量换算38,594

安全审计

VirusTotal

通过

ClawScan

通过

Static analysis

未展示

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills