[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QHZD0NXRMQC2FTEJM6374Y":3,"skill-same:01M6QHZD0NXRMQC2FTEJM6374Y":77},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":22,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":13,"repositoryHtmlUrl":60,"repositoryHomepageUrl":6,"ownerHtmlUrl":61,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":62,"install":63,"resources":76},"01M6QHZD0NXRMQC2FTEJM6374Y","generate-mock",null,"Master the art of creating effective mocks: when to mock, what to mock, and how to avoid over-mocking. This skill encapsulates the judgment of mock strategy, mock depth, and maintaining test reliability. Use when user mentions mocking, mocks, test doubles, stubbing, or when they're unsure about mock strategy. Triggers especially when user says \"should I mock this?\", \"how to mock\", \"mock strategy\", \"too many mocks\", or \"test mocks\".","ImaginerLabs\u002Fskill-manager","ImaginerLabs","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F214277308?v=4","01M6QGGDPNF15RMMT1RCFDH9FN","01M6QGGDTH5BY64DQ123NR8M33",0,"MIT","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Fcoding\u002Fgenerate-mock\u002FSKILL.md",[17],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",[23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"generate","generate mock","mock","triggers","test","depth","mocks","re","about","mocking","how","how to","coding","tests","judgment","master","Art","reliability","use","strategy","2026-11-10 10:12:30",false,"---\nname: generate-mock\ndescription: >-\n  Master the art of creating effective mocks: when to mock, what to mock, and how to avoid over-mocking. This skill encapsulates the judgment of mock strategy, mock depth, and maintaining test reliability. Use when user mentions mocking, mocks, test doubles, stubbing, or when they're unsure about mock strategy. Triggers especially when user says \"should I mock this?\", \"how to mock\", \"mock strategy\", \"too many mocks\", or \"test mocks\".\ncategory: coding\npriority: P1\ntrigger_patterns:\n  - \"should I mock this\"\n  - \"how to mock\"\n  - \"mock strategy\"\n  - \"too many mocks\"\n  - \"mocking in tests\"\n  - \"test doubles\"\n  - \"stubbing\"\n---\n\n# Generate Mock — Strategic Mocking Framework\n\n## Overview\n\nGenerate-mock is a **behavioral specification skill** that encapsulates the judgment of **when to mock, what to mock, how deeply to mock, and how to avoid common mocking pitfalls**.\n\nThis skill embodies the expertise of developers who've written both over-mocked fragile tests and well-balanced test strategies and know the difference.\n\n## Core Philosophy\n\n### The Mocking Paradox\n\n> \"Mocks are powerful tools that let you test units in isolation. But overuse turns your tests from 'verifying behavior' into 'verifying implementation details' — making refactoring harder, not easier.\"\n\n### The Mocking Value Matrix\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                    MOCKING DECISION MATRIX                    │\n│                                                               │\n│                    Slow\u002FExpensive      Fast\u002FCheap           │\n│  ┌────────────────┼─────────────────┬────────────────────┐  │\n│  │ External API   │   ✅ MOCK IT    │   ? CONSIDER      │  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ Database       │   ✅ MOCK IT    │   ? INTEGRATE     │  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ File System    │   ✅ MOCK IT    │   ? CONSIDER     │  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ Simple Helper  │   ? DON'T     │   ❌ DON'T MOCK   │  │\n│  │                │   (test it)     │   (test it directly)│  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ Shared Utils   │   ✅ MOCK IT    │   ? INTEGRATE    │  │\n│  └────────────────┴─────────────────┴────────────────────┘  │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Decision Framework\n\n### When to MOCK\n\n| Situation | Mock? | Rationale |\n|-----------|-------|-----------|\n| External API calls | ✅ Yes | Speed, reliability, cost |\n| Database operations | ✅ Yes | Speed, isolation |\n| File system access | ✅ Yes | Speed, platform issues |\n| Time\u002FDate | ✅ Yes | Determinism |\n| Random values | ✅ Yes | Reproducibility |\n| Complex calculations | ? Careful | May indicate design issue |\n| Business logic | ❌ No | Test the real thing |\n| Simple getters | ❌ No | Not worth it |\n| Core domain objects | ❌ No | Test real behavior |\n\n### When NOT to MOCK\n\n| Situation | Don't Mock | Alternative |\n|-----------|------------|-------------|\n| Simple one-liners | Mock adds noise | Test directly |\n| Business rules | Need real behavior | Use real objects |\n| Value objects | Cheap to create | Test directly |\n| Domain logic | Your core value | Integration test |\n| Config that rarely changes | May not be needed | Test with real config |\n\n### The Mock Decision Tree\n\n```\n                    ┌─ Is it slow or expensive?\n                    │   └─ NO → Continue\n                    │       └─ YES → MOCK\n                    │\n                    └─ Is it external (API, DB, FS)?\n                        └─ YES → MOCK\n                        └─ NO → Continue\n                                │\n                                └─ Is it complex to set up?\n                                    └─ YES → MOCK (or simplify)\n                                    └─ NO → Continue\n                                            │\n                                            └─ Does it affect what you're testing?\n                                                └─ YES → Don't mock, test together\n                                                └─ NO → MOCK\n```\n\n## Behavioral Specification\n\n### Phase 1: Mock Strategy Design\n\n#### 1.1 Identifying Mock Points\n\n```markdown\n## System Under Test (SUT) Analysis\n\nComponent: UserService.getUserById(id)\n\nDependencies identified:\n┌─────────────────────────────────────────────────────────────┐\n│                                                             │\n│    UserService ──► Database ──► Repository ──► [MOCK THIS] │\n│         │                                                    │\n│         └──► EmailService ──► [MOCK THIS]                   │\n│                                                             │\n│         └──► Logger ──► [MOCK THIS]                        │\n│                                                             │\n│         └──► Cache ──► [MOCK THIS]                         │\n│                                                             │\n└─────────────────────────────────────────────────────────────┘\n\nSUT: UserService.getUserById\nDirect: Nothing (this IS the unit)\nIndirect: Database, Email, Logger, Cache\n```\n\n#### 1.2 Mock Depth Strategy\n\n```typescript\n\u002F\u002F DEEP MOCK - Mock entire object\nconst mockRepo = {\n  findById: vi.fn(),\n  save: vi.fn(),\n  delete: vi.fn(),\n};\n\n\u002F\u002F PARTIAL MOCK - Mock specific methods\nconst mockRepo = {\n  findById: vi.fn(),\n  \u002F\u002F save, delete use real implementation\n};\n\n\u002F\u002F SPY - Real object, track calls\nconst realRepo = new UserRepository();\nconst mockRepo = vi.spyOn(realRepo, 'findById');\n```\n\n### Phase 2: Mock Implementation\n\n#### 2.1 Good Mock Patterns\n\n```typescript\n\u002F\u002F PATTERN 1: Factory for consistent mocks\nfunction createMockUserRepository(overrides?: Partial\u003CMockUserRepository>) {\n  return {\n    findById: vi.fn().mockResolvedValue(null),\n    findByEmail: vi.fn().mockResolvedValue(null),\n    save: vi.fn().mockImplementation((user) => Promise.resolve(user)),\n    delete: vi.fn().mockResolvedValue(true),\n    ...overrides,\n  };\n}\n\n\u002F\u002F Usage\nconst mockRepo = createMockUserRepository({\n  findById: vi.fn().mockResolvedValue(testUser),\n});\n```\n\n```typescript\n\u002F\u002F PATTERN 2: Mock with预设 return values\nconst mockApi = {\n  fetchUser: vi.fn()\n    .mockResolvedValueOnce({ id: 1, name: 'Alice' })  \u002F\u002F First call\n    .mockResolvedValueOnce({ id: 2, name: 'Bob' })    \u002F\u002F Second call\n    .mockRejectedValueOnce(new Error('Network error')) \u002F\u002F Third call fails\n};\n```\n\n#### 2.2 Mock Verification Patterns\n\n```typescript\n\u002F\u002F GOOD: Verify behavior, not implementation\nit('should call repository with correct id', async () => {\n  const mockRepo = createMockUserRepository();\n  const service = new UserService(mockRepo);\n\n  await service.getUserById('123');\n\n  expect(mockRepo.findById).toHaveBeenCalledWith('123');\n});\n\nit('should return user when found', async () => {\n  const mockRepo = createMockUserRepository({\n    findById: vi.fn().mockResolvedValue(testUser),\n  });\n  const service = new UserService(mockRepo);\n\n  const result = await service.getUserById('123');\n\n  expect(result).toEqual(testUser);\n});\n```\n\n### Phase 3: Anti-Patterns\n\n#### 3.1 Over-Mocking\n\n```typescript\n\u002F\u002F BAD: Too many mocks = testing implementation\nit('should call repo.findById then cache.set then logger.info', async () => {\n  const mockRepo = { findById: vi.fn().mockResolvedValue(user) };\n  const mockCache = { set: vi.fn().mockResolvedValue(undefined) };\n  const mockLogger = { info: vi.fn() };\n  const service = new UserService(mockRepo, mockCache, mockLogger);\n\n  await service.getUserById('123');\n\n  expect(mockRepo.findById).toHaveBeenCalled();\n  expect(mockCache.set).toHaveBeenCalled();\n  expect(mockLogger.info).toHaveBeenCalled(); \u002F\u002F ← This is fragile\n});\n\n\u002F\u002F GOOD: Test behavior, not implementation\nit('should return user and cache it', async () => {\n  const mockRepo = { findById: vi.fn().mockResolvedValue(user) };\n  const mockCache = { set: vi.fn().mockResolvedValue(undefined) };\n  const service = new UserService(mockRepo, mockCache);\n\n  const result = await service.getUserById('123');\n\n  expect(result).toEqual(user);\n  expect(mockCache.set).toHaveBeenCalledWith('user:123', user);\n  \u002F\u002F Implementation detail (repo call) not verified\n});\n```\n\n#### 3.2 Brittle Mocks\n\n```typescript\n\u002F\u002F BAD: Testing exact call order\nit('should call in order', () => {\n  const mock1 = vi.fn();\n  const mock2 = vi.fn();\n\n  process(mock1, mock2);\n\n  expect(mock1).toHaveBeenCalledTimes(1);\n  expect(mock2).toHaveBeenCalledTimes(1);\n  expect(mock1).toHaveBeenCalledBefore(mock2); \u002F\u002F ← Brittle!\n});\n\n\u002F\u002F GOOD: Test outcomes\nit('should complete processing', () => {\n  const mock1 = vi.fn();\n  const mock2 = vi.fn();\n\n  process(mock1, mock2);\n\n  expect(mock1).toHaveBeenCalled();\n  expect(mock2).toHaveBeenCalled();\n  \u002F\u002F Order doesn't matter for the outcome\n});\n```\n\n#### 3.3 Mocking What You Own\n\n```typescript\n\u002F\u002F BAD: Mocking internal modules\nimport { validateEmail } from '.\u002Fvalidators';\n\nit('should validate email', () => {\n  vi.mock('.\u002Fvalidators', () => ({\n    validateEmail: vi.fn().mockReturnValue(true),\n  }));\n  \u002F\u002F Now testing a mock, not real behavior\n});\n\n\u002F\u002F GOOD: Test real validation\nit('should validate email correctly', () => {\n  expect(validateEmail('test@example.com')).toBe(true);\n  expect(validateEmail('invalid')).toBe(false);\n});\n```\n\n### Phase 4: Mock Maintenance\n\n#### 4.1 Mock Hygiene Rules\n\n```markdown\nMOCK HYGIENE CHECKLIST\n=======================\n\n□ Mocks match the interface they're replacing\n□ Mock returns realistic data structures\n□ Mock handles edge cases (null, errors)\n□ Mock cleanup in afterEach or vi.clearAllMocks()\n□ Mocks are injected, not imported inline\n□ Mock assertions verify behavior, not implementation\n□ Mocks are documented when behavior is non-obvious\n□ Mocks fail tests when they're wrong, not silently succeed\n```\n\n#### 4.2 Mock Cleanup\n\n```typescript\n\u002F\u002F Use beforeEach\u002FafterEach for cleanup\nbeforeEach(() => {\n  vi.clearAllMocks();\n});\n\nafterEach(() => {\n  vi.restoreAllMocks();\n});\n\n\u002F\u002F Or reset specific mocks\nbeforeEach(() => {\n  mockRepository.findById.mockReset();\n});\n```\n\n## Mock Strategy Patterns\n\n### Pattern 1: Repository Pattern Mocks\n\n```typescript\n\u002F\u002F Interface-based mocking\ninterface IUserRepository {\n  findById(id: string): Promise\u003CUser | null>;\n  findByEmail(email: string): Promise\u003CUser | null>;\n  save(user: User): Promise\u003CUser>;\n}\n\n\u002F\u002F Mock implementation\nconst createMockUserRepository = (overrides?: Partial\u003CIUserRepository>) => ({\n  findById: vi.fn(),\n  findByEmail: vi.fn(),\n  save: vi.fn(),\n  ...overrides,\n});\n\n\u002F\u002F Usage in tests\nconst mockRepo = createMockUserRepository({\n  findById: vi.fn().mockResolvedValue(testUser),\n});\n```\n\n### Pattern 2: HTTP\u002FAPI Mocks\n\n```typescript\n\u002F\u002F Using MSW or similar\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\n\nconst server = setupServer(\n  rest.get('\u002Fapi\u002Fusers\u002F:id', (req, res, ctx) => {\n    return res(ctx.json({ id: req.params.id, name: 'Test User' }));\n  })\n);\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n```\n\n### Pattern 3: Time Mocks\n\n```typescript\n\u002F\u002F Mocking Date.now()\nconst mockDate = new Date('2024-04-17T12:00:00Z');\nvi.setSystemTime(mockDate);\n\n\u002F\u002F Or for specific Date calls\nvi.spyOn(Date, 'now').mockReturnValue(mockDate.getTime());\n```\n\n### Pattern 4: Config Mocks\n\n```typescript\n\u002F\u002F For feature flags, env vars, etc.\nvi.stubEnv('FEATURE_ENABLED', 'true');\nvi.stubEnv('API_URL', 'https:\u002F\u002Ftest.example.com');\n```\n\n## Common Scenarios\n\n### Scenario 1: \"Should I mock this external API call?\"\n\n```markdown\nAnalysis:\n- External API call\n- 500ms latency\n- Rate limited\n- Can fail intermittently\n\nMock Strategy:\n✅ YES - Mock it\n  - Speed up tests significantly\n  - Avoid rate limits\n  - Ensure deterministic tests\n\nMock Implementation:\n- Use msw for HTTP mocks\n- Create realistic response fixtures\n- Add error case mocks too\n```\n\n### Scenario 2: \"My tests are brittle because of too many mocks\"\n\n```markdown\nAnalysis:\n- 15 mocks in one test\n- 10+ assertions on mock calls\n- Refactoring breaks tests constantly\n\nProblem: Testing implementation details\n\nSolution:\n1. Reduce mock count - mock only external deps\n2. Test outcomes, not calls\n3. Use integration tests for internal interactions\n\nBefore:\nexpect(mock.validate).toHaveBeenCalledWith('input');\nexpect(mock.transform).toHaveBeenCalledWith(mock.validate());\nexpect(mock.save).toHaveBeenCalledWith(mock.transform());\n\nAfter:\nconst result = service.process('input');\nexpect(result).toEqual(expectedOutput);\n```\n\n### Scenario 3: \"Mock vs Integration test?\"\n\n```markdown\nDecision Framework:\n\nUNIT TEST (with mocks):\n- Testing a single function\n- Isolating from external dependencies\n- Fast feedback needed\n- Internal logic only\n\nINTEGRATION TEST (no mocks):\n- Testing multiple components together\n- Verifying data flow\n- Ensuring contracts work\n- Catching integration bugs\n\nHybrid Approach:\n- Unit tests for logic\n- Integration tests for component interaction\n- E2E for critical user paths\n```\n\n## The Mock Decision Checklist\n\n```\nMOCK DECISION CHECKLIST\n=======================\n\n□ Is this external? (API, DB, FS)\n  └─ YES → MOCK\n\n□ Is this slow or expensive?\n  └─ YES → MOCK\n\n□ Does this affect test reliability?\n  └─ YES → MOCK (date, random, time)\n\n□ Is this a simple helper function?\n  └─ YES → DON'T MOCK, test directly\n\n□ Is this core business logic?\n  └─ YES → DON'T MOCK, test with real objects\n\n□ Am I testing implementation details?\n  └─ YES → STOP, reconsider\n\n□ Will refactoring break this test?\n  └─ YES → Too brittle, reduce mocks\n```\n\n## Key Principles\n\n### 1. Mocks Are for Isolation\n\nMocks let you test one thing in isolation by replacing its dependencies.\n\n### 2. Don't Mock What You Own\n\nIf you control the code, test it directly or use real objects.\n\n### 3. Test Behavior, Not Implementation\n\nVerify outcomes, not the internal calls that lead to them.\n\n### 4. Mocks Should Match Reality\n\nMocks that return unrealistic data create false confidence.\n\n### 5. Keep Mocks Minimal\n\nThe more you mock, the more your tests become fragile.\n\n## Relationship to Other Skills\n\n- `test-think` — Determines what to test (and what to mock)\n- `setup-test-data` — Creates realistic test fixtures\n- `debug-test` — When mocked tests fail\n- `test-readability` — Clear test structure with mocks\n- `intelligent-test-creation` — Combines mock strategy with test design\n","# Generate Mock — Strategic Mocking Framework\n\n## Overview\n\nGenerate-mock is a **behavioral specification skill** that encapsulates the judgment of **when to mock, what to mock, how deeply to mock, and how to avoid common mocking pitfalls**.\n\nThis skill embodies the expertise of developers who've written both over-mocked fragile tests and well-balanced test strategies and know the difference.\n\n## Core Philosophy\n\n### The Mocking Paradox\n\n> \"Mocks are powerful tools that let you test units in isolation. But overuse turns your tests from 'verifying behavior' into 'verifying implementation details' — making refactoring harder, not easier.\"\n\n### The Mocking Value Matrix\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                    MOCKING DECISION MATRIX                    │\n│                                                               │\n│                    Slow\u002FExpensive      Fast\u002FCheap           │\n│  ┌────────────────┼─────────────────┬────────────────────┐  │\n│  │ External API   │   ✅ MOCK IT    │   ? CONSIDER      │  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ Database       │   ✅ MOCK IT    │   ? INTEGRATE     │  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ File System    │   ✅ MOCK IT    │   ? CONSIDER     │  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ Simple Helper  │   ? DON'T     │   ❌ DON'T MOCK   │  │\n│  │                │   (test it)     │   (test it directly)│  │\n│  ├────────────────┼─────────────────┼────────────────────┤  │\n│  │ Shared Utils   │   ✅ MOCK IT    │   ? INTEGRATE    │  │\n│  └────────────────┴─────────────────┴────────────────────┘  │\n└─────────────────────────────────────────────────────────────┘\n```\n\n## Decision Framework\n\n### When to MOCK\n\n| Situation | Mock? | Rationale |\n|-----------|-------|-----------|\n| External API calls | ✅ Yes | Speed, reliability, cost |\n| Database operations | ✅ Yes | Speed, isolation |\n| File system access | ✅ Yes | Speed, platform issues |\n| Time\u002FDate | ✅ Yes | Determinism |\n| Random values | ✅ Yes | Reproducibility |\n| Complex calculations | ? Careful | May indicate design issue |\n| Business logic | ❌ No | Test the real thing |\n| Simple getters | ❌ No | Not worth it |\n| Core domain objects | ❌ No | Test real behavior |\n\n### When NOT to MOCK\n\n| Situation | Don't Mock | Alternative |\n|-----------|------------|-------------|\n| Simple one-liners | Mock adds noise | Test directly |\n| Business rules | Need real behavior | Use real objects |\n| Value objects | Cheap to create | Test directly |\n| Domain logic | Your core value | Integration test |\n| Config that rarely changes | May not be needed | Test with real config |\n\n### The Mock Decision Tree\n\n```\n                    ┌─ Is it slow or expensive?\n                    │   └─ NO → Continue\n                    │       └─ YES → MOCK\n                    │\n                    └─ Is it external (API, DB, FS)?\n                        └─ YES → MOCK\n                        └─ NO → Continue\n                                │\n                                └─ Is it complex to set up?\n                                    └─ YES → MOCK (or simplify)\n                                    └─ NO → Continue\n                                            │\n                                            └─ Does it affect what you're testing?\n                                                └─ YES → Don't mock, test together\n                                                └─ NO → MOCK\n```\n\n## Behavioral Specification\n\n### Phase 1: Mock Strategy Design\n\n#### 1.1 Identifying Mock Points\n\n```markdown\n## System Under Test (SUT) Analysis\n\nComponent: UserService.getUserById(id)\n\nDependencies identified:\n┌─────────────────────────────────────────────────────────────┐\n│                                                             │\n│    UserService ──► Database ──► Repository ──► [MOCK THIS] │\n│         │                                                    │\n│         └──► EmailService ──► [MOCK THIS]                   │\n│                                                             │\n│         └──► Logger ──► [MOCK THIS]                        │\n│                                                             │\n│         └──► Cache ──► [MOCK THIS]                         │\n│                                                             │\n└─────────────────────────────────────────────────────────────┘\n\nSUT: UserService.getUserById\nDirect: Nothing (this IS the unit)\nIndirect: Database, Email, Logger, Cache\n```\n\n#### 1.2 Mock Depth Strategy\n\n```typescript\n\u002F\u002F DEEP MOCK - Mock entire object\nconst mockRepo = {\n  findById: vi.fn(),\n  save: vi.fn(),\n  delete: vi.fn(),\n};\n\n\u002F\u002F PARTIAL MOCK - Mock specific methods\nconst mockRepo = {\n  findById: vi.fn(),\n  \u002F\u002F save, delete use real implementation\n};\n\n\u002F\u002F SPY - Real object, track calls\nconst realRepo = new UserRepository();\nconst mockRepo = vi.spyOn(realRepo, 'findById');\n```\n\n### Phase 2: Mock Implementation\n\n#### 2.1 Good Mock Patterns\n\n```typescript\n\u002F\u002F PATTERN 1: Factory for consistent mocks\nfunction createMockUserRepository(overrides?: Partial\u003CMockUserRepository>) {\n  return {\n    findById: vi.fn().mockResolvedValue(null),\n    findByEmail: vi.fn().mockResolvedValue(null),\n    save: vi.fn().mockImplementation((user) => Promise.resolve(user)),\n    delete: vi.fn().mockResolvedValue(true),\n    ...overrides,\n  };\n}\n\n\u002F\u002F Usage\nconst mockRepo = createMockUserRepository({\n  findById: vi.fn().mockResolvedValue(testUser),\n});\n```\n\n```typescript\n\u002F\u002F PATTERN 2: Mock with预设 return values\nconst mockApi = {\n  fetchUser: vi.fn()\n    .mockResolvedValueOnce({ id: 1, name: 'Alice' })  \u002F\u002F First call\n    .mockResolvedValueOnce({ id: 2, name: 'Bob' })    \u002F\u002F Second call\n    .mockRejectedValueOnce(new Error('Network error')) \u002F\u002F Third call fails\n};\n```\n\n#### 2.2 Mock Verification Patterns\n\n```typescript\n\u002F\u002F GOOD: Verify behavior, not implementation\nit('should call repository with correct id', async () => {\n  const mockRepo = createMockUserRepository();\n  const service = new UserService(mockRepo);\n\n  await service.getUserById('123');\n\n  expect(mockRepo.findById).toHaveBeenCalledWith('123');\n});\n\nit('should return user when found', async () => {\n  const mockRepo = createMockUserRepository({\n    findById: vi.fn().mockResolvedValue(testUser),\n  });\n  const service = new UserService(mockRepo);\n\n  const result = await service.getUserById('123');\n\n  expect(result).toEqual(testUser);\n});\n```\n\n### Phase 3: Anti-Patterns\n\n#### 3.1 Over-Mocking\n\n```typescript\n\u002F\u002F BAD: Too many mocks = testing implementation\nit('should call repo.findById then cache.set then logger.info', async () => {\n  const mockRepo = { findById: vi.fn().mockResolvedValue(user) };\n  const mockCache = { set: vi.fn().mockResolvedValue(undefined) };\n  const mockLogger = { info: vi.fn() };\n  const service = new UserService(mockRepo, mockCache, mockLogger);\n\n  await service.getUserById('123');\n\n  expect(mockRepo.findById).toHaveBeenCalled();\n  expect(mockCache.set).toHaveBeenCalled();\n  expect(mockLogger.info).toHaveBeenCalled(); \u002F\u002F ← This is fragile\n});\n\n\u002F\u002F GOOD: Test behavior, not implementation\nit('should return user and cache it', async () => {\n  const mockRepo = { findById: vi.fn().mockResolvedValue(user) };\n  const mockCache = { set: vi.fn().mockResolvedValue(undefined) };\n  const service = new UserService(mockRepo, mockCache);\n\n  const result = await service.getUserById('123');\n\n  expect(result).toEqual(user);\n  expect(mockCache.set).toHaveBeenCalledWith('user:123', user);\n  \u002F\u002F Implementation detail (repo call) not verified\n});\n```\n\n#### 3.2 Brittle Mocks\n\n```typescript\n\u002F\u002F BAD: Testing exact call order\nit('should call in order', () => {\n  const mock1 = vi.fn();\n  const mock2 = vi.fn();\n\n  process(mock1, mock2);\n\n  expect(mock1).toHaveBeenCalledTimes(1);\n  expect(mock2).toHaveBeenCalledTimes(1);\n  expect(mock1).toHaveBeenCalledBefore(mock2); \u002F\u002F ← Brittle!\n});\n\n\u002F\u002F GOOD: Test outcomes\nit('should complete processing', () => {\n  const mock1 = vi.fn();\n  const mock2 = vi.fn();\n\n  process(mock1, mock2);\n\n  expect(mock1).toHaveBeenCalled();\n  expect(mock2).toHaveBeenCalled();\n  \u002F\u002F Order doesn't matter for the outcome\n});\n```\n\n#### 3.3 Mocking What You Own\n\n```typescript\n\u002F\u002F BAD: Mocking internal modules\nimport { validateEmail } from '.\u002Fvalidators';\n\nit('should validate email', () => {\n  vi.mock('.\u002Fvalidators', () => ({\n    validateEmail: vi.fn().mockReturnValue(true),\n  }));\n  \u002F\u002F Now testing a mock, not real behavior\n});\n\n\u002F\u002F GOOD: Test real validation\nit('should validate email correctly', () => {\n  expect(validateEmail('test@example.com')).toBe(true);\n  expect(validateEmail('invalid')).toBe(false);\n});\n```\n\n### Phase 4: Mock Maintenance\n\n#### 4.1 Mock Hygiene Rules\n\n```markdown\nMOCK HYGIENE CHECKLIST\n=======================\n\n□ Mocks match the interface they're replacing\n□ Mock returns realistic data structures\n□ Mock handles edge cases (null, errors)\n□ Mock cleanup in afterEach or vi.clearAllMocks()\n□ Mocks are injected, not imported inline\n□ Mock assertions verify behavior, not implementation\n□ Mocks are documented when behavior is non-obvious\n□ Mocks fail tests when they're wrong, not silently succeed\n```\n\n#### 4.2 Mock Cleanup\n\n```typescript\n\u002F\u002F Use beforeEach\u002FafterEach for cleanup\nbeforeEach(() => {\n  vi.clearAllMocks();\n});\n\nafterEach(() => {\n  vi.restoreAllMocks();\n});\n\n\u002F\u002F Or reset specific mocks\nbeforeEach(() => {\n  mockRepository.findById.mockReset();\n});\n```\n\n## Mock Strategy Patterns\n\n### Pattern 1: Repository Pattern Mocks\n\n```typescript\n\u002F\u002F Interface-based mocking\ninterface IUserRepository {\n  findById(id: string): Promise\u003CUser | null>;\n  findByEmail(email: string): Promise\u003CUser | null>;\n  save(user: User): Promise\u003CUser>;\n}\n\n\u002F\u002F Mock implementation\nconst createMockUserRepository = (overrides?: Partial\u003CIUserRepository>) => ({\n  findById: vi.fn(),\n  findByEmail: vi.fn(),\n  save: vi.fn(),\n  ...overrides,\n});\n\n\u002F\u002F Usage in tests\nconst mockRepo = createMockUserRepository({\n  findById: vi.fn().mockResolvedValue(testUser),\n});\n```\n\n### Pattern 2: HTTP\u002FAPI Mocks\n\n```typescript\n\u002F\u002F Using MSW or similar\nimport { rest } from 'msw';\nimport { setupServer } from 'msw\u002Fnode';\n\nconst server = setupServer(\n  rest.get('\u002Fapi\u002Fusers\u002F:id', (req, res, ctx) => {\n    return res(ctx.json({ id: req.params.id, name: 'Test User' }));\n  })\n);\n\nbeforeAll(() => server.listen());\nafterEach(() => server.resetHandlers());\nafterAll(() => server.close());\n```\n\n### Pattern 3: Time Mocks\n\n```typescript\n\u002F\u002F Mocking Date.now()\nconst mockDate = new Date('2024-04-17T12:00:00Z');\nvi.setSystemTime(mockDate);\n\n\u002F\u002F Or for specific Date calls\nvi.spyOn(Date, 'now').mockReturnValue(mockDate.getTime());\n```\n\n### Pattern 4: Config Mocks\n\n```typescript\n\u002F\u002F For feature flags, env vars, etc.\nvi.stubEnv('FEATURE_ENABLED', 'true');\nvi.stubEnv('API_URL', 'https:\u002F\u002Ftest.example.com');\n```\n\n## Common Scenarios\n\n### Scenario 1: \"Should I mock this external API call?\"\n\n```markdown\nAnalysis:\n- External API call\n- 500ms latency\n- Rate limited\n- Can fail intermittently\n\nMock Strategy:\n✅ YES - Mock it\n  - Speed up tests significantly\n  - Avoid rate limits\n  - Ensure deterministic tests\n\nMock Implementation:\n- Use msw for HTTP mocks\n- Create realistic response fixtures\n- Add error case mocks too\n```\n\n### Scenario 2: \"My tests are brittle because of too many mocks\"\n\n```markdown\nAnalysis:\n- 15 mocks in one test\n- 10+ assertions on mock calls\n- Refactoring breaks tests constantly\n\nProblem: Testing implementation details\n\nSolution:\n1. Reduce mock count - mock only external deps\n2. Test outcomes, not calls\n3. Use integration tests for internal interactions\n\nBefore:\nexpect(mock.validate).toHaveBeenCalledWith('input');\nexpect(mock.transform).toHaveBeenCalledWith(mock.validate());\nexpect(mock.save).toHaveBeenCalledWith(mock.transform());\n\nAfter:\nconst result = service.process('input');\nexpect(result).toEqual(expectedOutput);\n```\n\n### Scenario 3: \"Mock vs Integration test?\"\n\n```markdown\nDecision Framework:\n\nUNIT TEST (with mocks):\n- Testing a single function\n- Isolating from external dependencies\n- Fast feedback needed\n- Internal logic only\n\nINTEGRATION TEST (no mocks):\n- Testing multiple components together\n- Verifying data flow\n- Ensuring contracts work\n- Catching integration bugs\n\nHybrid Approach:\n- Unit tests for logic\n- Integration tests for component interaction\n- E2E for critical user paths\n```\n\n## The Mock Decision Checklist\n\n```\nMOCK DECISION CHECKLIST\n=======================\n\n□ Is this external? (API, DB, FS)\n  └─ YES → MOCK\n\n□ Is this slow or expensive?\n  └─ YES → MOCK\n\n□ Does this affect test reliability?\n  └─ YES → MOCK (date, random, time)\n\n□ Is this a simple helper function?\n  └─ YES → DON'T MOCK, test directly\n\n□ Is this core business logic?\n  └─ YES → DON'T MOCK, test with real objects\n\n□ Am I testing implementation details?\n  └─ YES → STOP, reconsider\n\n□ Will refactoring break this test?\n  └─ YES → Too brittle, reduce mocks\n```\n\n## Key Principles\n\n### 1. Mocks Are for Isolation\n\nMocks let you test one thing in isolation by replacing its dependencies.\n\n### 2. Don't Mock What You Own\n\nIf you control the code, test it directly or use real objects.\n\n### 3. Test Behavior, Not Implementation\n\nVerify outcomes, not the internal calls that lead to them.\n\n### 4. Mocks Should Match Reality\n\nMocks that return unrealistic data create false confidence.\n\n### 5. Keep Mocks Minimal\n\nThe more you mock, the more your tests become fragile.\n\n## Relationship to Other Skills\n\n- `test-think` — Determines what to test (and what to mock)\n- `setup-test-data` — Creates realistic test fixtures\n- `debug-test` — When mocked tests fail\n- `test-readability` — Clear test structure with mocks\n- `intelligent-test-creation` — Combines mock strategy with test design\n",{"name":5,"category":35,"priority":48,"description":7,"trigger_patterns":49},"P1",[50,51,52,53,54,55,56],"should I mock this","how to mock","mock strategy","too many mocks","mocking in tests","test doubles","stubbing","main","b9a52d8e27455bdad953d64928696d028223ea1b","skills\u002Fcoding\u002Fgenerate-mock","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager","https:\u002F\u002Fgithub.com\u002FImaginerLabs","2026-04-18 16:27:13",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add ImaginerLabs\u002Fskill-manager --skill generate-mock",{"tool":69,"command":70},"bunx","bunx skills add ImaginerLabs\u002Fskill-manager --skill generate-mock",{"tool":72,"command":73},"pnpm","pnpm dlx skills add ImaginerLabs\u002Fskill-manager --skill generate-mock","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Fcoding\u002Fgenerate-mock\u002FSKILL.md",true,[],[78,110,131,159,192,217],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":92,"publishedAt":43},"01M6QJCB2SD5KHC41ZDQC0GA1T","meeting-minutes","Generate concise, actionable meeting minutes for internal meetings. Includes metadata, attendees, agenda, decisions, action items (owner + due date), and follow-up steps.","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Fwriting\u002Fmeeting-minutes\u002FSKILL.md",[84,87],{"categoryNo":85,"categoryName":86,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":88,"categoryName":89,"taxonomyType":90,"taxonomyTypeDesc":91},"01JBSEEDCAT000000000000034","行政与办公人员","PROFESSION","适用职业",[93,94,95,96,97,98,23,99,100,101,80,57,102,103,104,105,106,107,108,109],"meeting minutes","meeting","minutes","writing","github","copilot","decisions","meetings","up","agenda","actionable","concise","follow-up","tree","true","action","for",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":43},"01M6QJC71RRGTGNNFEHJG6S20G","documentation-writer","Diátaxis Documentation Expert. An expert technical writer specializing in creating high-quality software documentation, guided by the principles and structure of the Diátaxis technical documentation authoring framework.","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Fwriting\u002Fdocumentation-writer\u002FSKILL.md",[],[117,118,119,96,97,98,120,121,122,123,124,125,57,126,127,128,129,106,107,130],"documentation","documentation writer","writer","https","quality","technical","technical writer","expert","documentation expert","structure","authoring","software","principles","high",{"skillNo":132,"name":133,"nameZh":6,"description":134,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":135,"categories":136,"keywords":144,"publishedAt":43},"01M6QJC0V3C7C4R9768J1AJYWY","doc-coauthoring","Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Fwriting\u002Fdoc-coauthoring\u002FSKILL.md",[137,140,141],{"categoryNo":138,"categoryName":139,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":85,"categoryName":86,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":142,"categoryName":143,"taxonomyType":90,"taxonomyTypeDesc":91},"01JBSEEDCAT000000000000036","内容创作者",[145,146,96,147,148,117,149,150,151,152,153,154,57,155,156,127,157,158,106,109],"doc coauthoring","doc","workflow","official","tasks","decision","write","context","proposals","guide","refine","iteration","trigger","co",{"skillNo":160,"name":161,"nameZh":6,"description":162,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":163,"categories":164,"keywords":173,"publishedAt":43},"01M6QJBJ0YPVEWGEXZH3PJRRTT","code-review-workflow","Executes comprehensive 4-phase code review: basic review, quality check, bundle analysis, and test coverage. Should be used when the user mentions comprehensive code review, checking code quality, or reviewing staged changes with multi-phase analysis. This is the comprehensive review workflow, distinct from focused skills like frontend-code-review, staged-code-review, or code-change-test-designer.","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Ftesting\u002Fcode-review-workflow\u002FSKILL.md",[165,168,169,170],{"categoryNo":166,"categoryName":167,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000007","代码审查",{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":85,"categoryName":86,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":171,"categoryName":172,"taxonomyType":90,"taxonomyTypeDesc":91},"01JBSEEDCAT000000000000030","开发工程师",[174,175,147,176,177,178,179,27,180,181,182,183,184,185,186,187,188,189,190,191],"code review","review","code","code review workflow","testing","frontend","change","code quality","code-review","analysis","check","coverage","quality check","basic","multi","comprehensive code review","with","phase",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":207,"publishedAt":43},"01M6QJB7XNHV3VEEQF4W7FMWF6","code-change-test-designer","Analyzes code changes and designs comprehensive test cases. Reads diffs, summarizes capability changes, and designs test cases covering main flows and edge cases. Should be used when the user mentions test coverage, designing tests for code changes, or analyzing diff\u002Fcommit for testing purposes. Distinguished from code-review-workflow which provides comprehensive review, this skill focuses on test case design for code changes.","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Ftesting\u002Fcode-change-test-designer\u002FSKILL.md",[198,199,202,203,204],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":200,"categoryName":201,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":85,"categoryName":86,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":171,"categoryName":172,"taxonomyType":90,"taxonomyTypeDesc":91},{"categoryNo":205,"categoryName":206,"taxonomyType":90,"taxonomyTypeDesc":91},"01JBSEEDCAT000000000000032","设计师",[27,180,176,208,209,178,210,211,147,212,182,213,185,214,57,36,215,216,109,191],"designer","code change test designer","design","diffs","commit","edge","diff","flows","which",{"skillNo":218,"name":219,"nameZh":6,"description":220,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":221,"categories":222,"keywords":224,"publishedAt":43},"01M6QJB195WD7DCJWDMKWKB29S","skill-creator","Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.","https:\u002F\u002Fgithub.com\u002FImaginerLabs\u002Fskill-manager\u002Fblob\u002Fmain\u002Fskills\u002Fmeta-skills\u002Fskill-creator\u002FSKILL.md",[223],{"categoryNo":85,"categoryName":86,"taxonomyType":20,"taxonomyTypeDesc":21},[225,226,227,228,148,229,230,231,232,233,183,234,235,236,57,237,238,106,109,219],"skill creator","creator","performance","run evals","variance analysis","create","run","benchmark","Meta","improve","edit","evals","optimize","existing skill"]