測試與除錯
測試和除錯是軟體開發中不可或缺的環節。傳統IDE需要手動編寫測試用例、反覆執行測試、設定斷點、分析日誌,過程繁瑣且耗時。Claude Code透過AI輔助,讓測試和除錯變得前所未有的高效。
本文全面介紹如何用Claude Code進行智慧化的測試生成、除錯分析和效能最佳化。
執行測試
基礎測試執行
最簡單的測試執行方式是直接告訴Claude Code:
运行所有的测试
Claude Code會:
- 自動檢測專案使用的測試框架(Jest、Mocha、Pytest等)
- 執行測試命令
- 收集並分析測試結果
- 提供清晰的測試報告
I'll run all tests for this project.
🧪 Test Suite: Jest
Running tests...
Test Results:
✓ 124 tests passed
✗ 3 tests failed
⏱️ Total time: 2.3s
Failed Tests:
1. UserController.createUser
- Expected status 201, got 500
- Error: Database connection timeout
2. PostService.getPosts
- Expected array length 5, got 3
- Missing posts with status 'draft'
3. AuthController.login
- Token validation failed
- JWT secret mismatch
Would you like me to investigate and fix these failures?
執行特定測試
針對特定功能的測試:
只运行用户相关的测试
Claude Code會智慧匹配相關測試:
Found 15 user-related test files:
Running user tests...
✓ tests/unit/user/UserModel.test.js (8/8 passed)
✓ tests/unit/user/UserValidator.test.js (6/6 passed)
✗ tests/integration/user/UserAPI.test.js (3/5 passed)
✓ tests/e2e/user/userFlow.test.js (4/4 passed)
Summary: 21/24 tests passed
Failed tests in UserAPI.test.js:
- POST /api/users (email uniqueness check)
- GET /api/users/:id (permission check)
- DELETE /api/users/:id (soft delete)
Focus on these 3 failures?
監視模式
讓測試在程式碼變化時自動執行:
以监视模式运行测试,代码修改后自动重新测试
Claude Code會:
npm test -- --watch --coverage
並持續監控測試結果:
Watch mode enabled. Watching for file changes...
[1st run] 124 passed, 3 failed
[App.js changed] Re-running...
[2nd run] 126 passed, 1 failed
[UserService.js changed] Re-running...
[3rd run] 127 passed, 0 failed ✓
All tests passing! Real-time coverage: 87%
測試覆蓋率分析
运行测试并生成覆盖率报告
Claude Code會執行完整的覆蓋率分析:
Running tests with coverage...
📊 Coverage Report:
File | Lines | Branch | Funcs | Statements
-------------------------+--------+--------+--------+------------
src/
controllers/
UserController.js | 92% | 85% | 100% | 93%
PostController.js | 78% | 70% | 88% | 80%
services/
UserService.js | 95% | 90% | 100% | 96%
PostService.js | 65% | 50% | 75% | 68% ⚠️
models/
User.js | 88% | 80% | 100% | 90%
Post.js | 85% | 75% | 92% | 87%
utils/
validator.js | 100% | 100% | 100% | 100% ✓
Overall Coverage | 86% | 78% | 94% | 87%
⚠️ Low coverage files:
- PostService.js (68% statements)
Missing: edge cases in deletePost, updatePost
Recommendation: Add tests for error scenarios
✓ Excellent coverage:
- validator.js (100%)
- UserService.js (96%)
View detailed HTML report: coverage/lcov-report/index.html