[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MG1JQ2FJMBJBJE10RJWKNV":3,"skill-same:01M6MG1JQ2FJMBJBJE10RJWKNV":61},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":28,"publishedAt":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":42,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M6MG1JQ2FJMBJBJE10RJWKNV","integration-testing",null,"hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1575,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fintegration-testing\u002FSKILL.md",[17,22,25],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":26,"categoryName":27,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口",[29,30,31],"testing","integration","integration testing","2026-11-10 10:12:30",false,"---\n\nname: qa\u002Fintegration-testing\ndescription: 集成测试方法论，验证模块间协作、数据库交互、服务间调用，参考 Testcontainers、Testing Library、WireMock 等开源实践\nversion: 1.0.0\nagent: qa\ntype: methodology\nuser-invocable: false\nagent-invocable: true\ndependencies:\n- shared\u002Ftech-stack-detection\n  triggers:\n- 需要验证模块间协作时\n- 需要测试数据库真实交互时\n- 需要测试服务间调用时\n- 需要验证前端组件与 API 集成时\n  metadata:\n  internal: true\n\n---\n\n# 集成测试方法论\n\n> 参考开源实践：Testcontainers、Testing Library、WireMock、Testcontainers-go、Django Test Client\n\n## 集成测试 vs 单元测试\n\n| 维度 | 单元测试       | 集成测试             |\n| ---- | -------------- | -------------------- |\n| 范围 | 单个函数\u002F组件  | 多个模块协作         |\n| 依赖 | Mock 外部依赖  | 真实依赖（DB、HTTP） |\n| 速度 | 快（ms）       | 较慢（s）            |\n| 目的 | 验证逻辑正确性 | 验证模块间协作       |\n| 数据 | Mock 数据      | 测试数据库\u002F真实数据  |\n\n## 1. 后端集成测试\n\n### 1.1 数据库集成测试\n\n使用真实数据库（Testcontainers 或测试数据库），不 mock Repository 层。\n\n#### Node.js + Testcontainers (PostgreSQL)\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FuserRepository.test.ts\nimport { PostgreSqlContainer } from '@testcontainers\u002Fpostgresql';\nimport { PrismaClient } from '@prisma\u002Fclient';\nimport { UserRepository } from '..\u002F..\u002Fsrc\u002Frepositories\u002FuserRepository';\n\ndescribe('UserRepository (integration)', () => {\n  let container: StartedPostgreSqlContainer;\n  let prisma: PrismaClient;\n  let repo: UserRepository;\n\n  beforeAll(async () => {\n    container = await new PostgreSqlContainer().start();\n    prisma = new PrismaClient({ datasources: { db: { url: container.getConnectionUri() } } });\n    await prisma.$executeRawUnsafe('CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"');\n    repo = new UserRepository(prisma);\n  }, 60000);\n\n  afterAll(async () => {\n    await prisma.$disconnect();\n    await container.stop();\n  }, 60000);\n\n  beforeEach(async () => {\n    await prisma.user.deleteMany();\n  });\n\n  it('creates and retrieves user', async () => {\n    const user = await repo.create({ name: 'Alice', email: 'alice@example.com' });\n    const found = await repo.findByEmail('alice@example.com');\n\n    expect(found?.id).toBe(user.id);\n    expect(found?.name).toBe('Alice');\n  });\n\n  it('returns null for non-existent email', async () => {\n    const found = await repo.findByEmail('nonexistent@example.com');\n    expect(found).toBeNull();\n  });\n});\n```\n\n#### Python + pytest (PostgreSQL)\n\n```python\n# tests\u002Fintegration\u002Ftest_user_repository.py\nimport pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom app.models import Base\nfrom app.repositories import UserRepository\n\n@pytest.fixture(scope=\"module\")\ndef db_session():\n    engine = create_engine(\"postgresql:\u002F\u002Ftest:test@localhost:5432\u002Ftest_db\")\n    Base.metadata.create_all(engine)\n    Session = sessionmaker(bind=engine)\n    session = Session()\n    yield session\n    session.close()\n    Base.metadata.drop_all(engine)\n\ndef test_create_and_get_user(db_session):\n    repo = UserRepository(db_session)\n    user = repo.create(name=\"Alice\", email=\"alice@example.com\")\n    found = repo.find_by_email(\"alice@example.com\")\n    assert found.id == user.id\n    assert found.name == \"Alice\"\n```\n\n### 1.2 API + DB 端到端集成\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Fuser-api.test.ts\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\nimport { prisma } from '..\u002F..\u002Fsrc\u002Fdb';\n\ndescribe('User API + DB integration', () => {\n  beforeAll(async () => {\n    await prisma.$connect();\n  });\n\n  afterAll(async () => {\n    await prisma.$disconnect();\n  });\n\n  beforeEach(async () => {\n    await prisma.user.deleteMany();\n  });\n\n  it('POST creates user in database', async () => {\n    const res = await request(app)\n      .post('\u002Fapi\u002Fusers')\n      .send({ name: 'Alice', email: 'alice@example.com' })\n      .expect(201);\n\n    \u002F\u002F 验证数据库中确实存在\n    const dbUser = await prisma.user.findUnique({ where: { id: res.body.data.id } });\n    expect(dbUser).not.toBeNull();\n    expect(dbUser?.name).toBe('Alice');\n  });\n\n  it('GET returns persisted user', async () => {\n    await prisma.user.create({ data: { name: 'Bob', email: 'bob@example.com' } });\n\n    const res = await request(app).get('\u002Fapi\u002Fusers').expect(200);\n    expect(res.body.data.items).toHaveLength(1);\n    expect(res.body.data.items[0].name).toBe('Bob');\n  });\n\n  it('DELETE removes user from database', async () => {\n    const user = await prisma.user.create({\n      data: { name: 'Charlie', email: 'charlie@example.com' },\n    });\n\n    await request(app).delete(`\u002Fapi\u002Fusers\u002F${user.id}`).expect(200);\n\n    const dbUser = await prisma.user.findUnique({ where: { id: user.id } });\n    expect(dbUser).toBeNull();\n  });\n});\n```\n\n### 1.3 服务间调用集成\n\n使用 WireMock 或 Mock Service Worker 模拟外部服务：\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Forder-service.test.ts\nimport { WireMock } from 'wiremock-captain';\n\ndescribe('OrderService integration with PaymentService', () => {\n  let wiremock: WireMock;\n\n  beforeAll(async () => {\n    wiremock = new WireMock('http:\u002F\u002Flocalhost:8080');\n  });\n\n  it('marks order as paid when payment succeeds', async () => {\n    \u002F\u002F Mock 支付服务成功响应\n    await wiremock.stubFor({\n      request: { method: 'POST', url: '\u002Fpayments' },\n      response: { status: 200, jsonBody: { success: true, transactionId: 'tx-123' } },\n    });\n\n    const order = await orderService.create({ userId: '1', items: [] });\n    const paid = await orderService.pay(order.id, { method: 'credit_card' });\n\n    expect(paid.status).toBe('paid');\n  });\n\n  it('keeps order pending when payment fails', async () => {\n    await wiremock.stubFor({\n      request: { method: 'POST', url: '\u002Fpayments' },\n      response: { status: 402, jsonBody: { error: 'INSUFFICIENT_FUNDS' } },\n    });\n\n    const order = await orderService.create({ userId: '1', items: [] });\n    await expect(orderService.pay(order.id, { method: 'credit_card' })).rejects.toThrow(\n      'Payment failed',\n    );\n\n    const refreshed = await orderService.getById(order.id);\n    expect(refreshed.status).toBe('pending');\n  });\n});\n```\n\n## 2. 前端集成测试\n\n### 2.1 组件 + 状态管理 + API 集成\n\n使用 Testing Library + MSW (Mock Service Worker)：\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FUserList.test.tsx\nimport { render, screen, waitFor } from '@testing-library\u002Freact';\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\nimport { UserList } from '..\u002F..\u002Fsrc\u002Fcomponents\u002FUserList';\n\nconst server = setupServer(\n  rest.get('\u002Fapi\u002Fusers', (req, res, ctx) =>\n    res(ctx.json({ data: { items: [{ id: '1', name: 'Alice', email: 'alice@example.com' }] } }))\n  )\n);\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n\ndescribe('UserList integration', () => {\n  it('fetches and displays users from API', async () => {\n    render(\u003CUserList \u002F>);\n\n    expect(screen.getByText('加载中...')).toBeInTheDocument();\n\n    await waitFor(() => {\n      expect(screen.getByText('Alice')).toBeInTheDocument();\n    });\n  });\n\n  it('shows error when API fails', async () => {\n    server.use(\n      rest.get('\u002Fapi\u002Fusers', (req, res, ctx) => res(ctx.status(500)))\n    );\n\n    render(\u003CUserList \u002F>);\n\n    await waitFor(() => {\n      expect(screen.getByText('加载失败')).toBeInTheDocument();\n    });\n  });\n});\n```\n\n### 2.2 完整表单提交流程\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FCreateUserForm.test.tsx\nimport { render, screen, fireEvent, waitFor } from '@testing-library\u002Freact';\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\nimport { CreateUserForm } from '..\u002F..\u002Fsrc\u002Fcomponents\u002FCreateUserForm';\n\nconst server = setupServer();\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n\ndescribe('CreateUserForm integration', () => {\n  it('submits form and shows success', async () => {\n    server.use(\n      rest.post('\u002Fapi\u002Fusers', (req, res, ctx) =>\n        res(ctx.status(201), ctx.json({ success: true, data: { id: '1' } }))\n      )\n    );\n\n    render(\u003CCreateUserForm \u002F>);\n\n    fireEvent.change(screen.getByLabelText('姓名'), { target: { value: 'Alice' } });\n    fireEvent.change(screen.getByLabelText('邮箱'), { target: { value: 'alice@example.com' } });\n    fireEvent.click(screen.getByRole('button', { name: '提交' }));\n\n    await waitFor(() => {\n      expect(screen.getByText('创建成功')).toBeInTheDocument();\n    });\n  });\n\n  it('shows validation errors from server', async () => {\n    server.use(\n      rest.post('\u002Fapi\u002Fusers', (req, res, ctx) =>\n        res(ctx.status(400), ctx.json({ error: { code: 'VALIDATION_ERROR', message: '邮箱格式错误' } }))\n      )\n    );\n\n    render(\u003CCreateUserForm \u002F>);\n    fireEvent.change(screen.getByLabelText('姓名'), { target: { value: 'Alice' } });\n    fireEvent.change(screen.getByLabelText('邮箱'), { target: { value: 'invalid' } });\n    fireEvent.click(screen.getByRole('button', { name: '提交' }));\n\n    await waitFor(() => {\n      expect(screen.getByText('邮箱格式错误')).toBeInTheDocument();\n    });\n  });\n});\n```\n\n### 2.3 React Context \u002F 状态管理集成\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FAuthFlow.test.tsx\nimport { render, screen, fireEvent, waitFor } from '@testing-library\u002Freact';\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\nimport { AuthProvider } from '..\u002F..\u002Fsrc\u002Fcontext\u002FAuthContext';\nimport { LoginPage } from '..\u002F..\u002Fsrc\u002Fpages\u002FLoginPage';\n\nconst server = setupServer();\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n\ndescribe('Auth flow integration', () => {\n  it('logs in and stores token in context', async () => {\n    server.use(\n      rest.post('\u002Fapi\u002Fauth\u002Flogin', (req, res, ctx) =>\n        res(ctx.json({ data: { token: '\u003CJWT_TOKEN>', user: { name: 'Alice' } } }))\n      )\n    );\n\n    render(\n      \u003CAuthProvider>\n        \u003CLoginPage \u002F>\n      \u003C\u002FAuthProvider>\n    );\n\n    fireEvent.change(screen.getByLabelText('邮箱'), { target: { value: 'alice@example.com' } });\n    fireEvent.change(screen.getByLabelText('密码'), { target: { value: '\u003CPASSWORD>' } });\n    fireEvent.click(screen.getByRole('button', { name: '登录' }));\n\n    await waitFor(() => {\n      expect(screen.getByText('欢迎，Alice')).toBeInTheDocument();\n    });\n  });\n});\n```\n\n## 3. 测试数据库策略\n\n### 3.1 方案选择\n\n| 方案                       | 适用场景       | 优点       | 缺点                     |\n| -------------------------- | -------------- | ---------- | ------------------------ |\n| **Testcontainers**         | 需要真实数据库 | 最接近生产 | 启动慢（5-10s）          |\n| **内存数据库** (H2\u002FSQLite) | 简单 CRUD      | 快         | 与生产 DB 行为可能不一致 |\n| **测试数据库**             | 已有测试环境   | 真实       | 需要维护                 |\n| **事务回滚**               | 单测级隔离     | 快、无残留 | 不支持跨事务测试         |\n\n### 3.2 数据清理策略\n\n```typescript\n\u002F\u002F 策略 1：每个测试前清理（推荐）\nbeforeEach(async () => {\n  await prisma.user.deleteMany();\n  await prisma.order.deleteMany();\n});\n\n\u002F\u002F 策略 2：事务回滚（更快）\nlet tx: Prisma.TransactionClient;\nbeforeEach(async () => {\n  tx = await prisma.$transaction(async (t) => t, { isolationLevel: 'Serializable' });\n});\nafterEach(async () => {\n  await tx.$rollback?.();\n});\n```\n\n## 4. 集成测试的 Mock 边界\n\n### 应该 Mock 的\n\n| 依赖                           | 原因               |\n| ------------------------------ | ------------------ |\n| 第三方 API（支付、邮件、短信） | 不可控、有成本     |\n| 外部微服务                     | 独立部署，不应耦合 |\n| 文件系统                       | 测试速度和隔离     |\n\n### 不应该 Mock 的\n\n| 依赖                      | 原因                           |\n| ------------------------- | ------------------------------ |\n| 数据库                    | 集成测试的核心就是验证 DB 交互 |\n| 应用内部服务              | 要验证模块间协作               |\n| HTTP 框架（Express\u002FNest） | 要验证路由和中间件             |\n| 验证库（Zod\u002FJoi）         | 要验证真实校验逻辑             |\n\n## 5. 跨前后端契约集成测试\n\n验证前端发送的 payload 与后端 schema 一致：\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Fcontract.test.ts\nimport { z } from 'zod';\n\n\u002F\u002F 后端定义的 User Schema\nconst CreateUserSchema = z.object({\n  name: z.string().min(1).max(100),\n  email: z.string().email(),\n});\n\n\u002F\u002F 前端表单提交的数据\nconst formData = { name: 'Alice', email: 'alice@example.com' };\n\nit('frontend form data matches backend schema', () => {\n  const result = CreateUserSchema.safeParse(formData);\n  expect(result.success).toBe(true);\n});\n```\n\n## 6. 集成测试性能优化\n\n```typescript\n\u002F\u002F 1. 只启动一次数据库容器（beforeAll）\nlet container: StartedPostgreSqlContainer;\nbeforeAll(async () => {\n  container = await new PostgreSqlContainer().start();\n}, 120000);\n\n\u002F\u002F 2. 复用数据库连接\n\u002F\u002F 3. 数据清理用 TRUNCATE 而非 DROP\u002FCREATE\nbeforeEach(async () => {\n  await prisma.$executeRawUnsafe('TRUNCATE TABLE users, orders RESTART IDENTITY CASCADE');\n});\n\n\u002F\u002F 4. 并行执行无依赖的测试\n\u002F\u002F jest.config.js: maxWorkers: '50%'\n```\n\n## 7. 检查清单\n\n后端集成测试：\n- [ ] 使用真实数据库（Testcontainers 或测试 DB）\n- [ ] 不 mock Repository\u002F数据访问层\n- [ ] 每个测试独立（数据隔离）\n- [ ] 第三方服务使用 WireMock\u002FMSW mock\n- [ ] 验证数据真实写入数据库\n- [ ] 验证跨模块调用链完整\n\n前端集成测试：\n- [ ] 使用 MSW mock API，不 mock 内部组件\n- [ ] 验证组件 + 状态管理 + API 调用链\n- [ ] 覆盖成功和失败场景\n- [ ] 验证用户可见的 UI 反馈\n- [ ] 不测试实现细节，测试用户行为\n","# 集成测试方法论\n\n> 参考开源实践：Testcontainers、Testing Library、WireMock、Testcontainers-go、Django Test Client\n\n## 集成测试 vs 单元测试\n\n| 维度 | 单元测试       | 集成测试             |\n| ---- | -------------- | -------------------- |\n| 范围 | 单个函数\u002F组件  | 多个模块协作         |\n| 依赖 | Mock 外部依赖  | 真实依赖（DB、HTTP） |\n| 速度 | 快（ms）       | 较慢（s）            |\n| 目的 | 验证逻辑正确性 | 验证模块间协作       |\n| 数据 | Mock 数据      | 测试数据库\u002F真实数据  |\n\n## 1. 后端集成测试\n\n### 1.1 数据库集成测试\n\n使用真实数据库（Testcontainers 或测试数据库），不 mock Repository 层。\n\n#### Node.js + Testcontainers (PostgreSQL)\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FuserRepository.test.ts\nimport { PostgreSqlContainer } from '@testcontainers\u002Fpostgresql';\nimport { PrismaClient } from '@prisma\u002Fclient';\nimport { UserRepository } from '..\u002F..\u002Fsrc\u002Frepositories\u002FuserRepository';\n\ndescribe('UserRepository (integration)', () => {\n  let container: StartedPostgreSqlContainer;\n  let prisma: PrismaClient;\n  let repo: UserRepository;\n\n  beforeAll(async () => {\n    container = await new PostgreSqlContainer().start();\n    prisma = new PrismaClient({ datasources: { db: { url: container.getConnectionUri() } } });\n    await prisma.$executeRawUnsafe('CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"');\n    repo = new UserRepository(prisma);\n  }, 60000);\n\n  afterAll(async () => {\n    await prisma.$disconnect();\n    await container.stop();\n  }, 60000);\n\n  beforeEach(async () => {\n    await prisma.user.deleteMany();\n  });\n\n  it('creates and retrieves user', async () => {\n    const user = await repo.create({ name: 'Alice', email: 'alice@example.com' });\n    const found = await repo.findByEmail('alice@example.com');\n\n    expect(found?.id).toBe(user.id);\n    expect(found?.name).toBe('Alice');\n  });\n\n  it('returns null for non-existent email', async () => {\n    const found = await repo.findByEmail('nonexistent@example.com');\n    expect(found).toBeNull();\n  });\n});\n```\n\n#### Python + pytest (PostgreSQL)\n\n```python\n# tests\u002Fintegration\u002Ftest_user_repository.py\nimport pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom app.models import Base\nfrom app.repositories import UserRepository\n\n@pytest.fixture(scope=\"module\")\ndef db_session():\n    engine = create_engine(\"postgresql:\u002F\u002Ftest:test@localhost:5432\u002Ftest_db\")\n    Base.metadata.create_all(engine)\n    Session = sessionmaker(bind=engine)\n    session = Session()\n    yield session\n    session.close()\n    Base.metadata.drop_all(engine)\n\ndef test_create_and_get_user(db_session):\n    repo = UserRepository(db_session)\n    user = repo.create(name=\"Alice\", email=\"alice@example.com\")\n    found = repo.find_by_email(\"alice@example.com\")\n    assert found.id == user.id\n    assert found.name == \"Alice\"\n```\n\n### 1.2 API + DB 端到端集成\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Fuser-api.test.ts\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\nimport { prisma } from '..\u002F..\u002Fsrc\u002Fdb';\n\ndescribe('User API + DB integration', () => {\n  beforeAll(async () => {\n    await prisma.$connect();\n  });\n\n  afterAll(async () => {\n    await prisma.$disconnect();\n  });\n\n  beforeEach(async () => {\n    await prisma.user.deleteMany();\n  });\n\n  it('POST creates user in database', async () => {\n    const res = await request(app)\n      .post('\u002Fapi\u002Fusers')\n      .send({ name: 'Alice', email: 'alice@example.com' })\n      .expect(201);\n\n    \u002F\u002F 验证数据库中确实存在\n    const dbUser = await prisma.user.findUnique({ where: { id: res.body.data.id } });\n    expect(dbUser).not.toBeNull();\n    expect(dbUser?.name).toBe('Alice');\n  });\n\n  it('GET returns persisted user', async () => {\n    await prisma.user.create({ data: { name: 'Bob', email: 'bob@example.com' } });\n\n    const res = await request(app).get('\u002Fapi\u002Fusers').expect(200);\n    expect(res.body.data.items).toHaveLength(1);\n    expect(res.body.data.items[0].name).toBe('Bob');\n  });\n\n  it('DELETE removes user from database', async () => {\n    const user = await prisma.user.create({\n      data: { name: 'Charlie', email: 'charlie@example.com' },\n    });\n\n    await request(app).delete(`\u002Fapi\u002Fusers\u002F${user.id}`).expect(200);\n\n    const dbUser = await prisma.user.findUnique({ where: { id: user.id } });\n    expect(dbUser).toBeNull();\n  });\n});\n```\n\n### 1.3 服务间调用集成\n\n使用 WireMock 或 Mock Service Worker 模拟外部服务：\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Forder-service.test.ts\nimport { WireMock } from 'wiremock-captain';\n\ndescribe('OrderService integration with PaymentService', () => {\n  let wiremock: WireMock;\n\n  beforeAll(async () => {\n    wiremock = new WireMock('http:\u002F\u002Flocalhost:8080');\n  });\n\n  it('marks order as paid when payment succeeds', async () => {\n    \u002F\u002F Mock 支付服务成功响应\n    await wiremock.stubFor({\n      request: { method: 'POST', url: '\u002Fpayments' },\n      response: { status: 200, jsonBody: { success: true, transactionId: 'tx-123' } },\n    });\n\n    const order = await orderService.create({ userId: '1', items: [] });\n    const paid = await orderService.pay(order.id, { method: 'credit_card' });\n\n    expect(paid.status).toBe('paid');\n  });\n\n  it('keeps order pending when payment fails', async () => {\n    await wiremock.stubFor({\n      request: { method: 'POST', url: '\u002Fpayments' },\n      response: { status: 402, jsonBody: { error: 'INSUFFICIENT_FUNDS' } },\n    });\n\n    const order = await orderService.create({ userId: '1', items: [] });\n    await expect(orderService.pay(order.id, { method: 'credit_card' })).rejects.toThrow(\n      'Payment failed',\n    );\n\n    const refreshed = await orderService.getById(order.id);\n    expect(refreshed.status).toBe('pending');\n  });\n});\n```\n\n## 2. 前端集成测试\n\n### 2.1 组件 + 状态管理 + API 集成\n\n使用 Testing Library + MSW (Mock Service Worker)：\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FUserList.test.tsx\nimport { render, screen, waitFor } from '@testing-library\u002Freact';\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\nimport { UserList } from '..\u002F..\u002Fsrc\u002Fcomponents\u002FUserList';\n\nconst server = setupServer(\n  rest.get('\u002Fapi\u002Fusers', (req, res, ctx) =>\n    res(ctx.json({ data: { items: [{ id: '1', name: 'Alice', email: 'alice@example.com' }] } }))\n  )\n);\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n\ndescribe('UserList integration', () => {\n  it('fetches and displays users from API', async () => {\n    render(\u003CUserList \u002F>);\n\n    expect(screen.getByText('加载中...')).toBeInTheDocument();\n\n    await waitFor(() => {\n      expect(screen.getByText('Alice')).toBeInTheDocument();\n    });\n  });\n\n  it('shows error when API fails', async () => {\n    server.use(\n      rest.get('\u002Fapi\u002Fusers', (req, res, ctx) => res(ctx.status(500)))\n    );\n\n    render(\u003CUserList \u002F>);\n\n    await waitFor(() => {\n      expect(screen.getByText('加载失败')).toBeInTheDocument();\n    });\n  });\n});\n```\n\n### 2.2 完整表单提交流程\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FCreateUserForm.test.tsx\nimport { render, screen, fireEvent, waitFor } from '@testing-library\u002Freact';\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\nimport { CreateUserForm } from '..\u002F..\u002Fsrc\u002Fcomponents\u002FCreateUserForm';\n\nconst server = setupServer();\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n\ndescribe('CreateUserForm integration', () => {\n  it('submits form and shows success', async () => {\n    server.use(\n      rest.post('\u002Fapi\u002Fusers', (req, res, ctx) =>\n        res(ctx.status(201), ctx.json({ success: true, data: { id: '1' } }))\n      )\n    );\n\n    render(\u003CCreateUserForm \u002F>);\n\n    fireEvent.change(screen.getByLabelText('姓名'), { target: { value: 'Alice' } });\n    fireEvent.change(screen.getByLabelText('邮箱'), { target: { value: 'alice@example.com' } });\n    fireEvent.click(screen.getByRole('button', { name: '提交' }));\n\n    await waitFor(() => {\n      expect(screen.getByText('创建成功')).toBeInTheDocument();\n    });\n  });\n\n  it('shows validation errors from server', async () => {\n    server.use(\n      rest.post('\u002Fapi\u002Fusers', (req, res, ctx) =>\n        res(ctx.status(400), ctx.json({ error: { code: 'VALIDATION_ERROR', message: '邮箱格式错误' } }))\n      )\n    );\n\n    render(\u003CCreateUserForm \u002F>);\n    fireEvent.change(screen.getByLabelText('姓名'), { target: { value: 'Alice' } });\n    fireEvent.change(screen.getByLabelText('邮箱'), { target: { value: 'invalid' } });\n    fireEvent.click(screen.getByRole('button', { name: '提交' }));\n\n    await waitFor(() => {\n      expect(screen.getByText('邮箱格式错误')).toBeInTheDocument();\n    });\n  });\n});\n```\n\n### 2.3 React Context \u002F 状态管理集成\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002FAuthFlow.test.tsx\nimport { render, screen, fireEvent, waitFor } from '@testing-library\u002Freact';\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\nimport { AuthProvider } from '..\u002F..\u002Fsrc\u002Fcontext\u002FAuthContext';\nimport { LoginPage } from '..\u002F..\u002Fsrc\u002Fpages\u002FLoginPage';\n\nconst server = setupServer();\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n\ndescribe('Auth flow integration', () => {\n  it('logs in and stores token in context', async () => {\n    server.use(\n      rest.post('\u002Fapi\u002Fauth\u002Flogin', (req, res, ctx) =>\n        res(ctx.json({ data: { token: '\u003CJWT_TOKEN>', user: { name: 'Alice' } } }))\n      )\n    );\n\n    render(\n      \u003CAuthProvider>\n        \u003CLoginPage \u002F>\n      \u003C\u002FAuthProvider>\n    );\n\n    fireEvent.change(screen.getByLabelText('邮箱'), { target: { value: 'alice@example.com' } });\n    fireEvent.change(screen.getByLabelText('密码'), { target: { value: '\u003CPASSWORD>' } });\n    fireEvent.click(screen.getByRole('button', { name: '登录' }));\n\n    await waitFor(() => {\n      expect(screen.getByText('欢迎，Alice')).toBeInTheDocument();\n    });\n  });\n});\n```\n\n## 3. 测试数据库策略\n\n### 3.1 方案选择\n\n| 方案                       | 适用场景       | 优点       | 缺点                     |\n| -------------------------- | -------------- | ---------- | ------------------------ |\n| **Testcontainers**         | 需要真实数据库 | 最接近生产 | 启动慢（5-10s）          |\n| **内存数据库** (H2\u002FSQLite) | 简单 CRUD      | 快         | 与生产 DB 行为可能不一致 |\n| **测试数据库**             | 已有测试环境   | 真实       | 需要维护                 |\n| **事务回滚**               | 单测级隔离     | 快、无残留 | 不支持跨事务测试         |\n\n### 3.2 数据清理策略\n\n```typescript\n\u002F\u002F 策略 1：每个测试前清理（推荐）\nbeforeEach(async () => {\n  await prisma.user.deleteMany();\n  await prisma.order.deleteMany();\n});\n\n\u002F\u002F 策略 2：事务回滚（更快）\nlet tx: Prisma.TransactionClient;\nbeforeEach(async () => {\n  tx = await prisma.$transaction(async (t) => t, { isolationLevel: 'Serializable' });\n});\nafterEach(async () => {\n  await tx.$rollback?.();\n});\n```\n\n## 4. 集成测试的 Mock 边界\n\n### 应该 Mock 的\n\n| 依赖                           | 原因               |\n| ------------------------------ | ------------------ |\n| 第三方 API（支付、邮件、短信） | 不可控、有成本     |\n| 外部微服务                     | 独立部署，不应耦合 |\n| 文件系统                       | 测试速度和隔离     |\n\n### 不应该 Mock 的\n\n| 依赖                      | 原因                           |\n| ------------------------- | ------------------------------ |\n| 数据库                    | 集成测试的核心就是验证 DB 交互 |\n| 应用内部服务              | 要验证模块间协作               |\n| HTTP 框架（Express\u002FNest） | 要验证路由和中间件             |\n| 验证库（Zod\u002FJoi）         | 要验证真实校验逻辑             |\n\n## 5. 跨前后端契约集成测试\n\n验证前端发送的 payload 与后端 schema 一致：\n\n```typescript\n\u002F\u002F tests\u002Fintegration\u002Fcontract.test.ts\nimport { z } from 'zod';\n\n\u002F\u002F 后端定义的 User Schema\nconst CreateUserSchema = z.object({\n  name: z.string().min(1).max(100),\n  email: z.string().email(),\n});\n\n\u002F\u002F 前端表单提交的数据\nconst formData = { name: 'Alice', email: 'alice@example.com' };\n\nit('frontend form data matches backend schema', () => {\n  const result = CreateUserSchema.safeParse(formData);\n  expect(result.success).toBe(true);\n});\n```\n\n## 6. 集成测试性能优化\n\n```typescript\n\u002F\u002F 1. 只启动一次数据库容器（beforeAll）\nlet container: StartedPostgreSqlContainer;\nbeforeAll(async () => {\n  container = await new PostgreSqlContainer().start();\n}, 120000);\n\n\u002F\u002F 2. 复用数据库连接\n\u002F\u002F 3. 数据清理用 TRUNCATE 而非 DROP\u002FCREATE\nbeforeEach(async () => {\n  await prisma.$executeRawUnsafe('TRUNCATE TABLE users, orders RESTART IDENTITY CASCADE');\n});\n\n\u002F\u002F 4. 并行执行无依赖的测试\n\u002F\u002F jest.config.js: maxWorkers: '50%'\n```\n\n## 7. 检查清单\n\n后端集成测试：\n- [ ] 使用真实数据库（Testcontainers 或测试 DB）\n- [ ] 不 mock Repository\u002F数据访问层\n- [ ] 每个测试独立（数据隔离）\n- [ ] 第三方服务使用 WireMock\u002FMSW mock\n- [ ] 验证数据真实写入数据库\n- [ ] 验证跨模块调用链完整\n\n前端集成测试：\n- [ ] 使用 MSW mock API，不 mock 内部组件\n- [ ] 验证组件 + 状态管理 + API 调用链\n- [ ] 覆盖成功和失败场景\n- [ ] 验证用户可见的 UI 反馈\n- [ ] 不测试实现细节，测试用户行为\n",{},"main","2b63f856ce19c2a797929cacabd9e0fc936812fa","plugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fintegration-testing",491,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-14 14:06:13",{"source":7,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill integration-testing",{"tool":53,"command":54},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill integration-testing",{"tool":56,"command":57},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill integration-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fintegration-testing\u002FSKILL.md",true,[],[62,72,80,88,96,104],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":67,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":71},"01M7DV332YQMGD8WTRJ9DZQXTB","worktable-review-with-annotations","Create, inspect, reply to, update, or resolve situated Worktable annotations. Use when feedback belongs to a Doc section, block, text range, or HTML Doc, or when the user asks to address existing review feedback and coordinate a requested artifact edit.","MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":76,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":71},"01M7DV2YGHCZVBEB1AHYB6CGHE","worktable-find-and-synthesize-context","Find, assess, and synthesize context from Worktable Docs and Records. Use when the user asks what a workspace contains, wants workspace-backed research, needs current facts reconciled across artifacts, or requests a cited synthesis without changing workspace state.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":84,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":71},"01M7DV2TQN1H11ME2SAF9MXN7V","worktable-create-or-update-docs","Create, edit, rename, or maintain narrative Worktable Docs. Use for plans, decisions, briefs, notes, research syntheses, and other durable prose when the user requests a new artifact or a safe update to an existing one.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":92,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":71},"01M7DV2NE452NEA8TXATKSNAJH","worktable-create-or-manage-records","Organize repeated structured information as durable Worktable Records. Use for research datasets, inventories, directories, pipelines, trackers, and other collections whose items need identity, fields, filtering, links, validation, or individual updates.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":100,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":71},"01M7DV2HENRBR2KSCVM064WH0Y","worktable-create-or-manage-interactive-html","Create or improve durable visual and interactive artifacts in Worktable. Use for dashboards, trackers, calculators, mini apps, slide presentations, and other requests that benefit from a polished HTML Doc.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":66,"licenseFileUrl":108,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":71},"01M7DV2CADR5R7RQFFYPNAGR9Y","worktable-collaborate-threads","Read, answer, and hand off messages through durable Worktable threads with users or other authenticated participants. Use when the user asks to check addressed messages, reply to a participant, continue a thread, request another agent's help, wait briefly for a response, or watch for comments and messages sent to the agent.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FSKILL.md",[],[]]