Token导航 LogoToken导航

Agent Skill · 研究检索

testing-patterns(测试模式)

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

testing-patterns 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 38,938。

总安装 1,490周安装 64GitHub Stars 3下载 522核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/dedalus-erp-pas/foundation-skills --skill testing-patterns

这个 Skill 是做什么的

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

提供全面测试策略与模式指南,覆盖单元、集成与端到端测试层级。包含 Mock、Stub 与测试替身最佳实践,优化测试可靠性与覆盖率。适合用于改进现有测试质量或建立新项目测试体系。需结合具体项目框架与运行环境实施,避免为通过而修改逻辑。

testing-patterns 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/testing-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/dedalus-erp-pas/foundation-skills --skill test…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

testing-patterns 怎么安装?

在终端执行 npx skills add https://github.com/dedalus-erp-pas/foundation-skills --skill testing-patter…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

testing-patterns 支持哪些 AI 工具?

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

testing-patterns 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

testing-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

testing-patterns 用的人多吗?

公开数据是累计安装 1,490 次,近一周安装 64 次,下载 522 次,GitHub 3 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

testing-patterns 安全吗?

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

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

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 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

测试模式 · 本页

1,4903需要联网未明确通过

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

SKILL.md 原文

Testing Patterns & Strategies

Comprehensive guide to testing JavaScript/TypeScript applications. Complements the tdd skill (which focuses on workflow) by providing concrete patterns, strategies, and anti-patterns.

When to Use This Skill

Activate when the user:

  • Wants to write tests for existing or new code
  • Needs to establish a testing strategy for a project
  • Wants to improve test coverage or reliability
  • Has flaky or brittle tests
  • Asks about mocking, stubbing, or test doubles
  • Needs guidance on unit vs integration vs E2E tests

Testing Pyramid

        /  E2E  \          Few, slow, high confidence
       /----------\
      / Integration \      Moderate count, medium speed
     /----------------\
    /      Unit        \   Many, fast, focused
   /____________________\

Rule of thumb: ~70% unit, ~20% integration, ~10% E2E. Adjust per project — legacy codebases often benefit from more integration tests initially.

1. Unit Testing Patterns

Test Structure: AAA (Arrange, Act, Assert)

describe('calculateDiscount', () => {
  it('should apply 10% discount for orders above 100€', () => {
    // Arrange
    const order = { total: 150, items: ['item1', 'item2'] }

    // Act
    const result = calculateDiscount(order)

    // Assert
    expect(result).toBe(135)
  })
})

Naming Convention

Use descriptive names that read as specifications:

// GOOD — describes behavior
it('should return 401 when token is expired')
it('should retry 3 times before failing')
it('should trim whitespace from patient name')

// BAD — describes implementation
it('should call validateToken')
it('should set retryCount to 3')
it('should use .trim()')

Parameterized Tests (Table-Driven)

describe('parseHL7Date', () => {
  it.each([
    ['20260315', new Date(2026, 2, 15)],
    ['20260315120000', new Date(2026, 2, 15, 12, 0, 0)],
    ['', null],
    ['invalid', null],
  ])('should parse "%s" to %s', (input, expected) => {
    expect(parseHL7Date(input)).toEqual(expected)
  })
})

Testing Error Cases

Always test the unhappy path:

describe('PatientService.findById', () => {
  it('should throw NotFoundError for unknown patient ID', async () => {
    await expect(service.findById('UNKNOWN'))
      .rejects.toThrow(NotFoundError)
  })

  it('should throw ValidationError for empty ID', async () => {
    await expect(service.findById(''))
      .rejects.toThrow(ValidationError)
  })
})

Testing Async Code

// Promises
it('should resolve with patient data', async () => {
  const patient = await fetchPatient('PAT123')
  expect(patient.name).toBe('DUPONT')
})

// Event emitters
it('should emit "transfer" event on unit change', (done) => {
  emitter.on('transfer', (data) => {
    expect(data.unit).toBe('CARDIO')
    done()
  })
  service.transferPatient('PAT123', 'CARDIO')
})

2. Integration Testing Patterns

Integration tests verify that components work together correctly.

Database Integration Tests

describe('PatientRepository', () => {
  let db: TestDatabase

  beforeAll(async () => {
    db = await TestDatabase.create()  // Real DB, not mock
    await db.migrate()
  })

  afterEach(async () => {
    await db.truncate()  // Clean between tests
  })

  afterAll(async () => {
    await db.destroy()
  })

  it('should persist and retrieve a patient', async () => {
    const repo = new PatientRepository(db.connection)

    await repo.create({
      id: 'PAT123',
      name: 'DUPONT',
      birthDate: '1975-03-15',
    })

    const found = await repo.findById('PAT123')
    expect(found).toMatchObject({
      id: 'PAT123',
      name: 'DUPONT',
    })
  })
})

API Integration Tests

describe('POST /api/patients', () => {
  it('should create a patient and return 201', async () => {
    const response = await request(app)
      .post('/api/patients')
      .send({ name: 'DUPONT', birthDate: '1975-03-15' })
      .set('Authorization', `Bearer ${validToken}`)

    expect(response.status).toBe(201)
    expect(response.body.data.id).toBeDefined()
  })

  it('should return 400 for missing required fields', async () => {
    const response = await request(app)
      .post('/api/patients')
      .send({})  // Missing name
      .set('Authorization', `Bearer ${validToken}`)

    expect(response.status).toBe(400)
    expect(response.body.errors).toContainEqual(
      expect.objectContaining({ field: 'name' })
    )
  })

  it('should return 401 without authentication', async () => {
    const response = await request(app)
      .post('/api/patients')
      .send({ name: 'DUPONT' })

    expect(response.status).toBe(401)
  })
})

Message Processing Integration Tests

Particularly relevant for healthcare message processing (HPK, HL7):

describe('HPK Message Pipeline', () => {
  it('should parse, validate, and transform an ID|M1 message', async () => {
    const rawMessage = 'ID|M1|C|HEXAGONE|20260122120000|USER001|PAT123|DUPONT|JEAN|19750315|M'

    const result = await pipeline.process(rawMessage)

    expect(result.type).toBe('ID')
    expect(result.code).toBe('M1')
    expect(result.patient.name).toBe('DUPONT')
    expect(result.valid).toBe(true)
  })
})

3. E2E Testing Patterns

E2E tests validate complete user workflows through the real application.

Page Object Pattern

class PatientListPage {
  constructor(private page: Page) {}

  async goto() {
    await this.page.goto('/patients')
  }

  async search(query: string) {
    await this.page.fill('[data-testid="search-input"]', query)
    await this.page.click('[data-testid="search-button"]')
  }

  async getResults() {
    return this.page.locator('[data-testid="patient-row"]').allTextContents()
  }

  async clickPatient(name: string) {
    await this.page.click(`text=${name}`)
  }
}

// Usage in test
test('should find patient by name', async ({ page }) => {
  const patientList = new PatientListPage(page)
  await patientList.goto()
  await patientList.search('DUPONT')

  const results = await patientList.getResults()
  expect(results).toContain('DUPONT JEAN')
})

Data-testid Convention

Use data-testid attributes for test selectors, never CSS classes or element structure:

// GOOD — stable selector
await page.click('[data-testid="submit-admission"]')

// BAD — brittle, breaks on style/structure changes
await page.click('.btn.btn-primary.submit')
await page.click('form > div:nth-child(3) > button')

Visual Regression Testing

test('patient dashboard matches snapshot', async ({ page }) => {
  await page.goto('/dashboard')
  await page.waitForLoadState('networkidle')
  await expect(page).toHaveScreenshot('dashboard.png', {
    maxDiffPixelRatio: 0.01,
  })
})

4. Mocking Strategies

When to Mock

MockDon't Mock
External HTTP APIsYour own database (use real test DB)
Time/Date (for determinism)Internal collaborators between modules
File system (when impractical)Simple utility functions
Third-party services (payment, email)Data transformations
Environment-specific featuresBusiness logic

Mock vs Stub vs Spy

// STUB — returns a fixed value
const getPatient = vi.fn().mockResolvedValue({ id: 'PAT123', name: 'DUPONT' })

// SPY — observes calls without changing behavior
const logSpy = vi.spyOn(logger, 'info')
await service.admitPatient(data)
expect(logSpy).toHaveBeenCalledWith('Patient admitted', { id: 'PAT123' })

// MOCK — replaces the entire module
vi.mock('./emailService', () => ({
  sendAdmissionNotification: vi.fn().mockResolvedValue(true),
}))

MSW for HTTP Mocking

Prefer MSW (Mock Service Worker) over manual fetch mocking:

import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
  http.get('/api/patients/:id', ({ params }) => {
    return HttpResponse.json({
      id: params.id,
      name: 'DUPONT',
      birthDate: '1975-03-15',
    })
  })
)

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

Time Mocking

describe('token expiration', () => {
  beforeEach(() => {
    vi.useFakeTimers()
  })

  afterEach(() => {
    vi.useRealTimers()
  })

  it('should reject expired tokens', () => {
    const token = createToken({ expiresIn: '1h' })

    vi.advanceTimersByTime(2 * 60 * 60 * 1000)  // 2 hours later

    expect(() => validateToken(token)).toThrow('Token expired')
  })
})

5. Test Organization

File Structure — Colocation

src/
├── patients/
│   ├── PatientService.ts
│   ├── PatientService.test.ts      # Unit tests next to source
│   ├── PatientRepository.ts
│   └── PatientRepository.test.ts
├── __tests__/
│   └── integration/
│       ├── patient-admission.test.ts    # Integration tests
│       └── hl7-message-flow.test.ts
└── e2e/
    ├── patient-workflow.spec.ts    # E2E tests
    └── pages/
        └── PatientListPage.ts     # Page objects

Test Utilities — Factories

Avoid copy-pasting test data. Use factories:

// test/factories/patient.ts
export function buildPatient(overrides: Partial<Patient> = {}): Patient {
  return {
    id: `PAT${Math.random().toString(36).slice(2, 8)}`,
    name: 'DUPONT',
    firstName: 'JEAN',
    birthDate: '1975-03-15',
    sex: 'M',
    ...overrides,
  }
}

// Usage
it('should flag underage patients', () => {
  const minor = buildPatient({ birthDate: '2015-06-01' })
  expect(isMinor(minor)).toBe(true)
})

6. Common Anti-Patterns

Testing Implementation Details

// BAD — tests internal state
it('should set isLoading to true', () => {
  component.fetchData()
  expect(component.state.isLoading).toBe(true)
})

// GOOD — tests observable behavior
it('should show loading spinner while fetching', async () => {
  render(<PatientList />)
  expect(screen.getByTestId('spinner')).toBeVisible()
  await waitForElementToBeRemoved(screen.queryByTestId('spinner'))
})

Excessive Mocking

// BAD — mocking everything, testing nothing real
it('should create patient', async () => {
  vi.mock('./db')
  vi.mock('./validator')
  vi.mock('./logger')
  // ... what are you even testing?
})

// GOOD — use real implementations, mock only boundaries
it('should create patient in database', async () => {
  const repo = new PatientRepository(testDb)
  const service = new PatientService(repo)  // Real repo, real DB

  const patient = await service.create({ name: 'DUPONT' })
  expect(patient.id).toBeDefined()
})

Flaky Test Patterns

Common causes and fixes:

CauseFix
Shared mutable stateUse beforeEach to reset state
Time-dependent testsUse vi.useFakeTimers()
Race conditions in async testsUse waitFor / findBy instead of getBy
Order-dependent testsEach test must be independent
Network calls in unit testsMock HTTP with MSW
Hardcoded portsUse dynamic port assignment

Snapshot Overuse

// BAD — meaningless snapshot of entire component
it('should render', () => {
  const { container } = render(<PatientCard patient={patient} />)
  expect(container).toMatchSnapshot()  // 200 lines of HTML nobody reads
})

// GOOD — targeted assertions
it('should display patient name and birthdate', () => {
  render(<PatientCard patient={patient} />)
  expect(screen.getByText('DUPONT JEAN')).toBeVisible()
  expect(screen.getByText('15/03/1975')).toBeVisible()
})

7. Testing Checklist

Before submitting a PR, verify:

[ ] New feature has tests covering happy path and error cases
[ ] Tests are independent — can run in any order
[ ] No flaky tests introduced (run suite 3x to verify)
[ ] Test names describe behavior, not implementation
[ ] Mocks are limited to external boundaries
[ ] No hardcoded test data — using factories
[ ] Test utilities are shared, not duplicated
[ ] Integration tests clean up after themselves
[ ] E2E tests use data-testid selectors
[ ] Coverage hasn't decreased

Framework Quick Reference

FrameworkBest ForCommand
VitestUnit + integration (Vite projects)vitest run
JestUnit + integration (legacy, CRA)jest --coverage
PlaywrightE2E, visual regressionplaywright test
CypressE2E, component testingcypress run
Testing LibraryDOM testing (React, Vue)Used with Vitest/Jest
MSWHTTP mockingUsed with any runner

平台分布

Codex

37.65%
按下载量换算197

Claude

26.99%
按下载量换算141

Cursor

18.83%
按下载量换算98

Gemini CLI

9.17%
按下载量换算48

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

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

继续浏览同类 Skills