← 教程列表
news

Anti-Pattern 3: Mocking Without Understanding

📅 2026/6/12 16:30:02⏱ 约 5 分钟阅读👁 7 阅读

**The violation:** ```typescript // ❌ BAD: Mock breaks test logic test('detects duplicate server', () => { // Mock prevents config write that test depends on! vi.mock('ToolCatalog', () => ({ discoverAndCacheTools: vi.fn().mockResolvedValue(undefined) })); await addServer(config); await addServer(config); // Should throw - but won't! }); ``` **Why this is wrong:** - Mocked method had side effect test depended on (writing config) - Over-mocking to "be safe" breaks actual behavior - Test passes for wrong reason or fails mysteriously **The fix:** ```typescript // ✅ GOOD: Mock at correct level test('detects duplicate server', () => { // Mock the slow part, preserve behavior test needs vi.mock('MCPServerManager'); // Just mock slow server startup await addServer(config); // Config written await addServer(config); // Duplicate detected ✓ }); ```

← 返回教程列表 AI8899 · 内容仅供学习参考