SITUATION: Writing Tests for Untested Code
Skill gerado a partir do pack templates-claude-code. Arquivo de origem: situacao/08-testes-codigo-sem-testes.md. Use como baseline e adapte ao projeto antes de mudancas grandes.
Conteudo do template
CONTEXT
Use this configuration when a codebase has zero or very few tests and you need to add them — without breaking existing behavior, and without being able to refactor first. The challenge: the code is often not written to be testable (global state, hardwired dependencies, no dependency injection). The goal is to add tests that work with the code as-is, not force an architectural rewrite.
OBJECTIVES
- Add tests that document and lock down existing behavior (correct or not)
- Identify the highest-risk paths and test those first
- Make the code incrementally more testable without big refactors
- Achieve meaningful coverage without testing trivial code
- Create a safety net that makes future refactoring safe
APPROACH RULES
Characterization tests first. Before writing tests that assert what "should" happen, write tests that assert what DOES happen. Run the code, observe output, write a test that captures it. This is the safety net — even if behavior is wrong, you want to know if it changes.
Start at the highest risk, not the lowest complexity. High risk = code that handles money, auth, data mutation, external integrations. A complex but low-risk rendering function can wait. Test what breaks the most when wrong.
Test the boundary, not the implementation. Test inputs and outputs. Don't test internal state or private methods. If you have to, the architecture needs to change later.
Identify seams. A seam is a place where you can substitute behavior without editing code (constructor injection, module mock, env variable). Find all seams before writing tests. If a class has no seams, you'll need to add a minimal one.
One failing test at a time. When adding tests, add one, make it pass, commit. Don't write 50 tests then try to make them all pass — the feedback loop is too long.
Mock at the outermost boundary. Mock database connections, HTTP calls, filesystems. Do not mock your own business logic — those are integration tests in disguise.
Coverage targets by risk tier:
- Critical (payments, auth, data deletion): 100% line + branch coverage
- Core business logic: 80%+ coverage
- Utility functions: 60%+ coverage
- Simple glue code / configuration: skip or minimal
ROUTING TABLE
| If you encounter |
Then |
| Global mutable state |
Wrap in a function or class that can be reset. Add a reset() method. Test in isolation. |
new SomeService() inside a function (hardwired dependency) |
Pass it as a parameter with a default. This is the minimal seam you need. |
| Database calls in the middle of business logic |
Extract DB calls to a Repository interface. Mock the repository in unit tests. |
| HTTP calls in business logic |
Extract to a client class. Mock it. Or use nock/msw to intercept at the HTTP layer. |
| Timer-dependent code (setTimeout, intervals) |
Use Jest's fake timers (jest.useFakeTimers()) or sinon fake timers. |
| File system operations |
Mock fs module or use a temp directory with cleanup in afterEach |
| Untestable legacy function (500 lines, everything mixed) |
Write a characterization test at the top level only. Add TODO comment. Refactor in a separate PR. |
| A function that's never called in tests (0% coverage) |
Write a smoke test: does it run without throwing? Then add edge cases. |
| Async code without proper async/await |
Convert to async/await first. Then test with async test functions. |
| Third-party library with complex behavior |
Test your code's behavior assuming the library works. Use stubs/fakes, not mocks of internals. |
Test Pyramid Strategy
E2E Tests (5%)
→ Cover the most critical user journeys only
→ Slow, flaky if overdone. Use sparingly.
Integration Tests (25%)
→ Test how components work together
→ Use real DB (in-memory or test DB), mock external APIs
→ Example: UserService creates a user and can retrieve it
Unit Tests (70%)
→ Test individual functions/classes in isolation
→ Fast, no I/O, fully mocked dependencies
→ Example: validateEmail() returns false for malformed email
Test Naming Convention
// Pattern: [unit] should [expected behavior] when [condition]
describe('AuthService', () => {
describe('login()', () => {
it('should return JWT token when credentials are valid', async () => { ... })
it('should throw UnauthorizedError when password is wrong', async () => { ... })
it('should throw UnauthorizedError when user does not exist', async () => { ... })
it('should lock account after 5 failed attempts', async () => { ... })
})
})
DO NOT
- DO NOT mock what you own — mock external dependencies, not your own services in unit tests
- DO NOT test private methods directly — if you feel you need to, the class has too many responsibilities
- DO NOT write tests that depend on execution order — each test must be independent
- DO NOT use
beforeAll for mutable state — use beforeEach so each test starts clean
- DO NOT target 100% line coverage across the board — it leads to testing trivial code while missing critical logic
- DO NOT write assertions that test the mock itself (
expect(mockFn).toHaveBeenCalled only) — test the outcome
- DO NOT leave
console.log in test files — tests should be silent in CI
- DO NOT skip flaky tests with
xtest or .skip — fix the flakiness or delete the test
OUTPUT FORMAT
When adding tests to an existing codebase, produce:
- Coverage Report — before and after, focusing on critical paths
- Test inventory — list of what's tested and what's intentionally not tested
- Seams identified — places where the code was adjusted (minimally) to be testable
- Characterization tests list — tests that capture current behavior (possibly wrong/to be revisited)
- Skipped paths — what was NOT tested and why (complexity, risk, time)
Template for a characterization test comment:
// CHARACTERIZATION TEST: Captures current behavior as of 2024-01-15.
// This behavior may not be correct — see issue #123.
// Do not change this test without first verifying the business requirement.
it('should return null when user not found (current behavior)', () => {
expect(service.getUser(-1)).toBeNull()
})
QUALITY GATES
1---2name: tpl-situacao-testes-codigo-sem-testes3description: Template do pack (situacao/08-testes-codigo-sem-testes.md). Orienta o agente em tarefas situacionais como debug, seguranca e refactor alinhado a esse contexto.4metadata:5 source: https://skillmd.com/skills/artubss/tpl-situacao-testes-codigo-sem-testes6 version: 1.0.07 source_template: situacao/08-testes-codigo-sem-testes.md8 generated_by: install_pack_templates_as_claude_skills9---1011# SITUATION: Writing Tests for Untested Code1213Skill gerado a partir do pack `templates-claude-code`. Arquivo de origem: `situacao/08-testes-codigo-sem-testes.md`. Use como baseline e adapte ao projeto antes de mudancas grandes.1415## Conteudo do template1617## CONTEXT18Use this configuration when a codebase has zero or very few tests and you need to add them — without breaking existing behavior, and without being able to refactor first. The challenge: the code is often not written to be testable (global state, hardwired dependencies, no dependency injection). The goal is to add tests that work with the code as-is, not force an architectural rewrite.1920## OBJECTIVES21- Add tests that document and lock down existing behavior (correct or not)22- Identify the highest-risk paths and test those first23- Make the code incrementally more testable without big refactors24- Achieve meaningful coverage without testing trivial code25- Create a safety net that makes future refactoring safe2627## APPROACH RULES28291. **Characterization tests first.** Before writing tests that assert what "should" happen, write tests that assert what DOES happen. Run the code, observe output, write a test that captures it. This is the safety net — even if behavior is wrong, you want to know if it changes.30312. **Start at the highest risk, not the lowest complexity.** High risk = code that handles money, auth, data mutation, external integrations. A complex but low-risk rendering function can wait. Test what breaks the most when wrong.32333. **Test the boundary, not the implementation.** Test inputs and outputs. Don't test internal state or private methods. If you have to, the architecture needs to change later.34354. **Identify seams.** A seam is a place where you can substitute behavior without editing code (constructor injection, module mock, env variable). Find all seams before writing tests. If a class has no seams, you'll need to add a minimal one.36375. **One failing test at a time.** When adding tests, add one, make it pass, commit. Don't write 50 tests then try to make them all pass — the feedback loop is too long.38396. **Mock at the outermost boundary.** Mock database connections, HTTP calls, filesystems. Do not mock your own business logic — those are integration tests in disguise.40417. **Coverage targets by risk tier:**42 - Critical (payments, auth, data deletion): 100% line + branch coverage43 - Core business logic: 80%+ coverage44 - Utility functions: 60%+ coverage45 - Simple glue code / configuration: skip or minimal4647## ROUTING TABLE4849| If you encounter | Then |50|-----------------|------|51| Global mutable state | Wrap in a function or class that can be reset. Add a `reset()` method. Test in isolation. |52| `new SomeService()` inside a function (hardwired dependency) | Pass it as a parameter with a default. This is the minimal seam you need. |53| Database calls in the middle of business logic | Extract DB calls to a Repository interface. Mock the repository in unit tests. |54| HTTP calls in business logic | Extract to a client class. Mock it. Or use `nock`/`msw` to intercept at the HTTP layer. |55| Timer-dependent code (setTimeout, intervals) | Use Jest's fake timers (`jest.useFakeTimers()`) or sinon fake timers. |56| File system operations | Mock `fs` module or use a temp directory with cleanup in `afterEach` |57| Untestable legacy function (500 lines, everything mixed) | Write a characterization test at the top level only. Add TODO comment. Refactor in a separate PR. |58| A function that's never called in tests (0% coverage) | Write a smoke test: does it run without throwing? Then add edge cases. |59| Async code without proper async/await | Convert to async/await first. Then test with async test functions. |60| Third-party library with complex behavior | Test your code's behavior assuming the library works. Use stubs/fakes, not mocks of internals. |6162## Test Pyramid Strategy6364```65E2E Tests (5%)66 → Cover the most critical user journeys only67 → Slow, flaky if overdone. Use sparingly.6869Integration Tests (25%)70 → Test how components work together71 → Use real DB (in-memory or test DB), mock external APIs72 → Example: UserService creates a user and can retrieve it7374Unit Tests (70%)75 → Test individual functions/classes in isolation76 → Fast, no I/O, fully mocked dependencies77 → Example: validateEmail() returns false for malformed email78```7980## Test Naming Convention8182```javascript83// Pattern: [unit] should [expected behavior] when [condition]84describe('AuthService', () => {85 describe('login()', () => {86 it('should return JWT token when credentials are valid', async () => { ... })87 it('should throw UnauthorizedError when password is wrong', async () => { ... })88 it('should throw UnauthorizedError when user does not exist', async () => { ... })89 it('should lock account after 5 failed attempts', async () => { ... })90 })91})92```9394## DO NOT9596- **DO NOT** mock what you own — mock external dependencies, not your own services in unit tests97- **DO NOT** test private methods directly — if you feel you need to, the class has too many responsibilities98- **DO NOT** write tests that depend on execution order — each test must be independent99- **DO NOT** use `beforeAll` for mutable state — use `beforeEach` so each test starts clean100- **DO NOT** target 100% line coverage across the board — it leads to testing trivial code while missing critical logic101- **DO NOT** write assertions that test the mock itself (`expect(mockFn).toHaveBeenCalled` only) — test the outcome102- **DO NOT** leave `console.log` in test files — tests should be silent in CI103- **DO NOT** skip flaky tests with `xtest` or `.skip` — fix the flakiness or delete the test104105## OUTPUT FORMAT106107When adding tests to an existing codebase, produce:1081091. **Coverage Report** — before and after, focusing on critical paths1102. **Test inventory** — list of what's tested and what's intentionally not tested1113. **Seams identified** — places where the code was adjusted (minimally) to be testable1124. **Characterization tests list** — tests that capture current behavior (possibly wrong/to be revisited)1135. **Skipped paths** — what was NOT tested and why (complexity, risk, time)114115Template for a characterization test comment:116```javascript117// CHARACTERIZATION TEST: Captures current behavior as of 2024-01-15.118// This behavior may not be correct — see issue #123.119// Do not change this test without first verifying the business requirement.120it('should return null when user not found (current behavior)', () => {121 expect(service.getUser(-1)).toBeNull()122})123```124125## QUALITY GATES126127- [ ] Coverage of critical paths (auth, payments, data mutations) is ≥ 90%128- [ ] Every test is independent: passes when run alone and in any order129- [ ] No test takes more than 200ms (if so, investigate why)130- [ ] No production code was changed to make tests pass (only seams added)131- [ ] All tests are named with the `should [behavior] when [condition]` pattern132- [ ] Test suite runs cleanly in CI with zero flaky failures133- [ ] Characterization tests are marked as such with a comment134- [ ] Coverage report visible in CI output135- [ ] A new developer can understand what a function does by reading its tests