@kurokeita/add-skill 1.17.2 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/skills/gh-fix-ci/SKILL.md +13 -5
- package/dist/skills/grill-me/SKILL.md +9 -0
- package/dist/skills/prd-to-tasks/SKILL.md +164 -0
- package/dist/skills/statusline-setup/SKILL.md +479 -0
- package/dist/skills/test-driven-development/SKILL.md +70 -345
- package/dist/skills/test-driven-development/deep-modules.md +33 -0
- package/dist/skills/test-driven-development/interface-design.md +35 -0
- package/dist/skills/test-driven-development/mocking.md +68 -0
- package/dist/skills/test-driven-development/refactoring.md +10 -0
- package/dist/skills/test-driven-development/tests.md +61 -0
- package/dist/skills/write-prd/SKILL.md +162 -0
- package/package.json +1 -1
- package/dist/skills/test-driven-development/testing-anti-patterns.md +0 -316
|
@@ -1,389 +1,114 @@
|
|
|
1
1
|
---
|
|
2
|
-
name:
|
|
3
|
-
description: Use when
|
|
2
|
+
name: tdd
|
|
3
|
+
description: Test-driven development with red-green-refactor loop. Use when user wants to build features or fix bugs using TDD, mentions "red-green-refactor", wants integration tests, or asks for test-first development.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
# Test-Driven Development
|
|
6
|
+
# Test-Driven Development
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## Philosophy
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
**Core principle**: Tests should verify behavior through public interfaces, not implementation details. Code can change entirely; tests shouldn't.
|
|
11
11
|
|
|
12
|
-
**
|
|
12
|
+
**Good tests** are integration-style: they exercise real code paths through public APIs. They describe _what_ the system does, not _how_ it does it. A good test reads like a specification - "user can checkout with valid cart" tells you exactly what capability exists. These tests survive refactors because they don't care about internal structure.
|
|
13
13
|
|
|
14
|
-
**
|
|
14
|
+
**Bad tests** are coupled to implementation. They mock internal collaborators, test private methods, or verify through external means (like querying a database directly instead of using the interface). The warning sign: your test breaks when you refactor, but behavior hasn't changed. If you rename an internal function and tests fail, those tests were testing implementation, not behavior.
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
See [tests.md](tests.md) for examples and [mocking.md](mocking.md) for mocking guidelines.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
## Anti-Pattern: Horizontal Slices
|
|
19
19
|
|
|
20
|
-
-
|
|
21
|
-
- Bug fixes
|
|
22
|
-
- Refactoring
|
|
23
|
-
- Behavior changes
|
|
20
|
+
**DO NOT write all tests first, then all implementation.** This is "horizontal slicing" - treating RED as "write all tests" and GREEN as "write all code."
|
|
24
21
|
|
|
25
|
-
|
|
22
|
+
This produces **crap tests**:
|
|
26
23
|
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
-
|
|
24
|
+
- Tests written in bulk test _imagined_ behavior, not _actual_ behavior
|
|
25
|
+
- You end up testing the _shape_ of things (data structures, function signatures) rather than user-facing behavior
|
|
26
|
+
- Tests become insensitive to real changes - they pass when behavior breaks, fail when behavior is fine
|
|
27
|
+
- You outrun your headlights, committing to test structure before understanding the implementation
|
|
30
28
|
|
|
31
|
-
|
|
29
|
+
**Correct approach**: Vertical slices via tracer bullets. One test → one implementation → repeat. Each test responds to what you learned from the previous cycle. Because you just wrote the code, you know exactly what behavior matters and how to verify it.
|
|
32
30
|
|
|
33
|
-
## The Iron Law
|
|
34
|
-
|
|
35
|
-
```
|
|
36
|
-
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
|
|
37
31
|
```
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
Implement fresh from tests. Period.
|
|
49
|
-
|
|
50
|
-
## Red-Green-Refactor
|
|
51
|
-
|
|
52
|
-
```dot
|
|
53
|
-
digraph tdd_cycle {
|
|
54
|
-
rankdir=LR;
|
|
55
|
-
red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
|
|
56
|
-
verify_red [label="Verify fails\ncorrectly", shape=diamond];
|
|
57
|
-
green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
|
|
58
|
-
verify_green [label="Verify passes\nAll green", shape=diamond];
|
|
59
|
-
refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
|
|
60
|
-
next [label="Next", shape=ellipse];
|
|
61
|
-
|
|
62
|
-
red -> verify_red;
|
|
63
|
-
verify_red -> green [label="yes"];
|
|
64
|
-
verify_red -> red [label="wrong\nfailure"];
|
|
65
|
-
green -> verify_green;
|
|
66
|
-
verify_green -> refactor [label="yes"];
|
|
67
|
-
verify_green -> green [label="no"];
|
|
68
|
-
refactor -> verify_green [label="stay\ngreen"];
|
|
69
|
-
verify_green -> next;
|
|
70
|
-
next -> red;
|
|
71
|
-
}
|
|
32
|
+
WRONG (horizontal):
|
|
33
|
+
RED: test1, test2, test3, test4, test5
|
|
34
|
+
GREEN: impl1, impl2, impl3, impl4, impl5
|
|
35
|
+
|
|
36
|
+
RIGHT (vertical):
|
|
37
|
+
RED→GREEN: test1→impl1
|
|
38
|
+
RED→GREEN: test2→impl2
|
|
39
|
+
RED→GREEN: test3→impl3
|
|
40
|
+
...
|
|
72
41
|
```
|
|
73
42
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
Write one minimal test showing what should happen.
|
|
77
|
-
|
|
78
|
-
<Good>
|
|
79
|
-
```typescript
|
|
80
|
-
test('retries failed operations 3 times', async () => {
|
|
81
|
-
let attempts = 0;
|
|
82
|
-
const operation = () => {
|
|
83
|
-
attempts++;
|
|
84
|
-
if (attempts < 3) throw new Error('fail');
|
|
85
|
-
return 'success';
|
|
86
|
-
};
|
|
43
|
+
## Workflow
|
|
87
44
|
|
|
88
|
-
|
|
45
|
+
### 1. Planning
|
|
89
46
|
|
|
90
|
-
|
|
91
|
-
expect(attempts).toBe(3);
|
|
92
|
-
});
|
|
47
|
+
Before writing any code:
|
|
93
48
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
test('retry works', async () => {
|
|
101
|
-
const mock = jest.fn()
|
|
102
|
-
.mockRejectedValueOnce(new Error())
|
|
103
|
-
.mockRejectedValueOnce(new Error())
|
|
104
|
-
.mockResolvedValueOnce('success');
|
|
105
|
-
await retryOperation(mock);
|
|
106
|
-
expect(mock).toHaveBeenCalledTimes(3);
|
|
107
|
-
});
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
Vague name, tests mock not code
|
|
111
|
-
</Bad>
|
|
49
|
+
- [ ] Confirm with user what interface changes are needed
|
|
50
|
+
- [ ] Confirm with user which behaviors to test (prioritize)
|
|
51
|
+
- [ ] Identify opportunities for [deep modules](deep-modules.md) (small interface, deep implementation)
|
|
52
|
+
- [ ] Design interfaces for [testability](interface-design.md)
|
|
53
|
+
- [ ] List the behaviors to test (not implementation steps)
|
|
54
|
+
- [ ] Get user approval on the plan
|
|
112
55
|
|
|
113
|
-
|
|
56
|
+
Ask: "What should the public interface look like? Which behaviors are most important to test?"
|
|
114
57
|
|
|
115
|
-
|
|
116
|
-
- Clear name
|
|
117
|
-
- Real code (no mocks unless unavoidable)
|
|
58
|
+
**You can't test everything.** Confirm with the user exactly which behaviors matter most. Focus testing effort on critical paths and complex logic, not every possible edge case.
|
|
118
59
|
|
|
119
|
-
###
|
|
60
|
+
### 2. Tracer Bullet
|
|
120
61
|
|
|
121
|
-
|
|
62
|
+
Write ONE test that confirms ONE thing about the system:
|
|
122
63
|
|
|
123
|
-
```bash
|
|
124
|
-
npm test path/to/test.test.ts
|
|
125
64
|
```
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
- Failure message is expected
|
|
131
|
-
- Fails because feature missing (not typos)
|
|
132
|
-
|
|
133
|
-
**Test passes?** You're testing existing behavior. Fix test.
|
|
134
|
-
|
|
135
|
-
**Test errors?** Fix error, re-run until it fails correctly.
|
|
136
|
-
|
|
137
|
-
### GREEN - Minimal Code
|
|
138
|
-
|
|
139
|
-
Write simplest code to pass the test.
|
|
140
|
-
|
|
141
|
-
<Good>
|
|
142
|
-
```typescript
|
|
143
|
-
async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
|
|
144
|
-
for (let i = 0; i < 3; i++) {
|
|
145
|
-
try {
|
|
146
|
-
return await fn();
|
|
147
|
-
} catch (e) {
|
|
148
|
-
if (i === 2) throw e;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
throw new Error('unreachable');
|
|
152
|
-
}
|
|
153
|
-
```
|
|
154
|
-
Just enough to pass
|
|
155
|
-
</Good>
|
|
156
|
-
|
|
157
|
-
<Bad>
|
|
158
|
-
```typescript
|
|
159
|
-
async function retryOperation<T>(
|
|
160
|
-
fn: () => Promise<T>,
|
|
161
|
-
options?: {
|
|
162
|
-
maxRetries?: number;
|
|
163
|
-
backoff?: 'linear' | 'exponential';
|
|
164
|
-
onRetry?: (attempt: number) => void;
|
|
165
|
-
}
|
|
166
|
-
): Promise<T> {
|
|
167
|
-
// YAGNI
|
|
168
|
-
}
|
|
169
|
-
```
|
|
170
|
-
Over-engineered
|
|
171
|
-
</Bad>
|
|
172
|
-
|
|
173
|
-
Don't add features, refactor other code, or "improve" beyond the test.
|
|
174
|
-
|
|
175
|
-
### Verify GREEN - Watch It Pass
|
|
176
|
-
|
|
177
|
-
**MANDATORY.**
|
|
178
|
-
|
|
179
|
-
```bash
|
|
180
|
-
npm test path/to/test.test.ts
|
|
65
|
+
RED: Write test for first behavior
|
|
66
|
+
↓ RUN TESTS — confirm it fails for the right reason
|
|
67
|
+
GREEN: Write minimal code to pass
|
|
68
|
+
↓ RUN TESTS — confirm it passes
|
|
181
69
|
```
|
|
182
70
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
- Test passes
|
|
186
|
-
- Other tests still pass
|
|
187
|
-
- Output pristine (no errors, warnings)
|
|
188
|
-
|
|
189
|
-
**Test fails?** Fix code, not test.
|
|
190
|
-
|
|
191
|
-
**Other tests fail?** Fix now.
|
|
192
|
-
|
|
193
|
-
### REFACTOR - Clean Up
|
|
194
|
-
|
|
195
|
-
After green only:
|
|
196
|
-
|
|
197
|
-
- Remove duplication
|
|
198
|
-
- Improve names
|
|
199
|
-
- Extract helpers
|
|
200
|
-
|
|
201
|
-
Keep tests green. Don't add behavior.
|
|
202
|
-
|
|
203
|
-
### Repeat
|
|
204
|
-
|
|
205
|
-
Next failing test for next feature.
|
|
206
|
-
|
|
207
|
-
## Good Tests
|
|
208
|
-
|
|
209
|
-
| Quality | Good | Bad |
|
|
210
|
-
|---------|------|-----|
|
|
211
|
-
| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
|
|
212
|
-
| **Clear** | Name describes behavior | `test('test1')` |
|
|
213
|
-
| **Shows intent** | Demonstrates desired API | Obscures what code should do |
|
|
214
|
-
|
|
215
|
-
## Why Order Matters
|
|
216
|
-
|
|
217
|
-
**"I'll write tests after to verify it works"**
|
|
218
|
-
|
|
219
|
-
Tests written after code pass immediately. Passing immediately proves nothing:
|
|
220
|
-
|
|
221
|
-
- Might test wrong thing
|
|
222
|
-
- Might test implementation, not behavior
|
|
223
|
-
- Might miss edge cases you forgot
|
|
224
|
-
- You never saw it catch the bug
|
|
225
|
-
|
|
226
|
-
Test-first forces you to see the test fail, proving it actually tests something.
|
|
227
|
-
|
|
228
|
-
**"I already manually tested all the edge cases"**
|
|
71
|
+
This is your tracer bullet - proves the path works end-to-end.
|
|
229
72
|
|
|
230
|
-
|
|
73
|
+
**You MUST run the test before writing any implementation.** A test that was never observed to fail might always pass vacuously, be testing the wrong thing, or be broken. The failure message tells you what the test is actually checking.
|
|
231
74
|
|
|
232
|
-
|
|
233
|
-
- Can't re-run when code changes
|
|
234
|
-
- Easy to forget cases under pressure
|
|
235
|
-
- "It worked when I tried it" ≠ comprehensive
|
|
75
|
+
### 3. Incremental Loop
|
|
236
76
|
|
|
237
|
-
|
|
77
|
+
For each remaining behavior:
|
|
238
78
|
|
|
239
|
-
**"Deleting X hours of work is wasteful"**
|
|
240
|
-
|
|
241
|
-
Sunk cost fallacy. The time is already gone. Your choice now:
|
|
242
|
-
|
|
243
|
-
- Delete and rewrite with TDD (X more hours, high confidence)
|
|
244
|
-
- Keep it and add tests after (30 min, low confidence, likely bugs)
|
|
245
|
-
|
|
246
|
-
The "waste" is keeping code you can't trust. Working code without real tests is technical debt.
|
|
247
|
-
|
|
248
|
-
**"TDD is dogmatic, being pragmatic means adapting"**
|
|
249
|
-
|
|
250
|
-
TDD IS pragmatic:
|
|
251
|
-
|
|
252
|
-
- Finds bugs before commit (faster than debugging after)
|
|
253
|
-
- Prevents regressions (tests catch breaks immediately)
|
|
254
|
-
- Documents behavior (tests show how to use code)
|
|
255
|
-
- Enables refactoring (change freely, tests catch breaks)
|
|
256
|
-
|
|
257
|
-
"Pragmatic" shortcuts = debugging in production = slower.
|
|
258
|
-
|
|
259
|
-
**"Tests after achieve the same goals - it's spirit not ritual"**
|
|
260
|
-
|
|
261
|
-
No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"
|
|
262
|
-
|
|
263
|
-
Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.
|
|
264
|
-
|
|
265
|
-
Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).
|
|
266
|
-
|
|
267
|
-
30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.
|
|
268
|
-
|
|
269
|
-
## Common Rationalizations
|
|
270
|
-
|
|
271
|
-
| Excuse | Reality |
|
|
272
|
-
|--------|---------|
|
|
273
|
-
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
|
|
274
|
-
| "I'll test after" | Tests passing immediately prove nothing. |
|
|
275
|
-
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
|
|
276
|
-
| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
|
|
277
|
-
| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
|
|
278
|
-
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
|
|
279
|
-
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
|
|
280
|
-
| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
|
|
281
|
-
| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
|
|
282
|
-
| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
|
|
283
|
-
| "Existing code has no tests" | You're improving it. Add tests for existing code. |
|
|
284
|
-
|
|
285
|
-
## Red Flags - STOP and Start Over
|
|
286
|
-
|
|
287
|
-
- Code before test
|
|
288
|
-
- Test after implementation
|
|
289
|
-
- Test passes immediately
|
|
290
|
-
- Can't explain why test failed
|
|
291
|
-
- Tests added "later"
|
|
292
|
-
- Rationalizing "just this once"
|
|
293
|
-
- "I already manually tested it"
|
|
294
|
-
- "Tests after achieve the same purpose"
|
|
295
|
-
- "It's about spirit not ritual"
|
|
296
|
-
- "Keep as reference" or "adapt existing code"
|
|
297
|
-
- "Already spent X hours, deleting is wasteful"
|
|
298
|
-
- "TDD is dogmatic, I'm being pragmatic"
|
|
299
|
-
- "This is different because..."
|
|
300
|
-
|
|
301
|
-
**All of these mean: Delete code. Start over with TDD.**
|
|
302
|
-
|
|
303
|
-
## Example: Bug Fix
|
|
304
|
-
|
|
305
|
-
**Bug:** Empty email accepted
|
|
306
|
-
|
|
307
|
-
**RED**
|
|
308
|
-
|
|
309
|
-
```typescript
|
|
310
|
-
test('rejects empty email', async () => {
|
|
311
|
-
const result = await submitForm({ email: '' });
|
|
312
|
-
expect(result.error).toBe('Email required');
|
|
313
|
-
});
|
|
314
|
-
```
|
|
315
|
-
|
|
316
|
-
**Verify RED**
|
|
317
|
-
|
|
318
|
-
```bash
|
|
319
|
-
$ npm test
|
|
320
|
-
FAIL: expected 'Email required', got undefined
|
|
321
79
|
```
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
function submitForm(data: FormData) {
|
|
327
|
-
if (!data.email?.trim()) {
|
|
328
|
-
return { error: 'Email required' };
|
|
329
|
-
}
|
|
330
|
-
// ...
|
|
331
|
-
}
|
|
332
|
-
```
|
|
333
|
-
|
|
334
|
-
**Verify GREEN**
|
|
335
|
-
|
|
336
|
-
```bash
|
|
337
|
-
$ npm test
|
|
338
|
-
PASS
|
|
80
|
+
RED: Write next test
|
|
81
|
+
↓ RUN TESTS — confirm new test fails, existing pass
|
|
82
|
+
GREEN: Minimal code to pass
|
|
83
|
+
↓ RUN TESTS — confirm all pass
|
|
339
84
|
```
|
|
340
85
|
|
|
341
|
-
|
|
342
|
-
Extract validation for multiple fields if needed.
|
|
343
|
-
|
|
344
|
-
## Verification Checklist
|
|
345
|
-
|
|
346
|
-
Before marking work complete:
|
|
347
|
-
|
|
348
|
-
- [ ] Every new function/method has a test
|
|
349
|
-
- [ ] Watched each test fail before implementing
|
|
350
|
-
- [ ] Each test failed for expected reason (feature missing, not typo)
|
|
351
|
-
- [ ] Wrote minimal code to pass each test
|
|
352
|
-
- [ ] All tests pass
|
|
353
|
-
- [ ] Output pristine (no errors, warnings)
|
|
354
|
-
- [ ] Tests use real code (mocks only if unavoidable)
|
|
355
|
-
- [ ] Edge cases and errors covered
|
|
356
|
-
|
|
357
|
-
Can't check all boxes? You skipped TDD. Start over.
|
|
86
|
+
Rules:
|
|
358
87
|
|
|
359
|
-
|
|
88
|
+
- One test at a time
|
|
89
|
+
- Run tests after writing each test (confirm RED) and after each implementation step (confirm GREEN)
|
|
90
|
+
- Only enough code to pass current test
|
|
91
|
+
- Don't anticipate future tests
|
|
92
|
+
- Keep tests focused on observable behavior
|
|
360
93
|
|
|
361
|
-
|
|
362
|
-
|---------|----------|
|
|
363
|
-
| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
|
|
364
|
-
| Test too complicated | Design too complicated. Simplify interface. |
|
|
365
|
-
| Must mock everything | Code too coupled. Use dependency injection. |
|
|
366
|
-
| Test setup huge | Extract helpers. Still complex? Simplify design. |
|
|
94
|
+
### 4. Refactor
|
|
367
95
|
|
|
368
|
-
|
|
96
|
+
After all tests pass, look for [refactor candidates](refactoring.md):
|
|
369
97
|
|
|
370
|
-
|
|
98
|
+
- [ ] Extract duplication
|
|
99
|
+
- [ ] Deepen modules (move complexity behind simple interfaces)
|
|
100
|
+
- [ ] Apply SOLID principles where natural
|
|
101
|
+
- [ ] Consider what new code reveals about existing code
|
|
102
|
+
- [ ] Run tests after each refactor step
|
|
371
103
|
|
|
372
|
-
Never
|
|
104
|
+
**Never refactor while RED.** Get to GREEN first.
|
|
373
105
|
|
|
374
|
-
##
|
|
375
|
-
|
|
376
|
-
When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
|
|
377
|
-
|
|
378
|
-
- Testing mock behavior instead of real behavior
|
|
379
|
-
- Adding test-only methods to production classes
|
|
380
|
-
- Mocking without understanding dependencies
|
|
381
|
-
|
|
382
|
-
## Final Rule
|
|
106
|
+
## Checklist Per Cycle
|
|
383
107
|
|
|
384
108
|
```
|
|
385
|
-
|
|
386
|
-
|
|
109
|
+
[ ] Test describes behavior, not implementation
|
|
110
|
+
[ ] Test uses public interface only
|
|
111
|
+
[ ] Test would survive internal refactor
|
|
112
|
+
[ ] Code is minimal for this test
|
|
113
|
+
[ ] No speculative features added
|
|
387
114
|
```
|
|
388
|
-
|
|
389
|
-
No exceptions without your human partner's permission.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Deep Modules
|
|
2
|
+
|
|
3
|
+
From "A Philosophy of Software Design":
|
|
4
|
+
|
|
5
|
+
**Deep module** = small interface + lots of implementation
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
┌─────────────────────┐
|
|
9
|
+
│ Small Interface │ ← Few methods, simple params
|
|
10
|
+
├─────────────────────┤
|
|
11
|
+
│ │
|
|
12
|
+
│ │
|
|
13
|
+
│ Deep Implementation│ ← Complex logic hidden
|
|
14
|
+
│ │
|
|
15
|
+
│ │
|
|
16
|
+
└─────────────────────┘
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
**Shallow module** = large interface + little implementation (avoid)
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
┌─────────────────────────────────┐
|
|
23
|
+
│ Large Interface │ ← Many methods, complex params
|
|
24
|
+
├─────────────────────────────────┤
|
|
25
|
+
│ Thin Implementation │ ← Just passes through
|
|
26
|
+
└─────────────────────────────────┘
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
When designing interfaces, ask:
|
|
30
|
+
|
|
31
|
+
- Can I reduce the number of methods?
|
|
32
|
+
- Can I simplify the parameters?
|
|
33
|
+
- Can I hide more complexity inside?
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Interface Design for Testability
|
|
2
|
+
|
|
3
|
+
Good interfaces make testing natural:
|
|
4
|
+
|
|
5
|
+
1. **Accept dependencies, don't create them**
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
// Testable
|
|
9
|
+
function processOrder(order, paymentGateway) {}
|
|
10
|
+
|
|
11
|
+
// Hard to test
|
|
12
|
+
function processOrder(order) {
|
|
13
|
+
const gateway = new StripeGateway();
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
2. **Return results, don't produce side effects**
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
// Testable
|
|
21
|
+
function calculateDiscount(cart): Discount {}
|
|
22
|
+
|
|
23
|
+
// Hard to test
|
|
24
|
+
function applyDiscount(cart): void {
|
|
25
|
+
cart.total -= discount;
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
3. **Small surface area**
|
|
30
|
+
- Fewer methods = fewer tests needed
|
|
31
|
+
- Fewer params = simpler test setup
|
|
32
|
+
|
|
33
|
+
4. **Keep test-only helpers out of production APIs**
|
|
34
|
+
|
|
35
|
+
If cleanup or inspection logic exists only for tests, put it in test utilities rather than adding methods to production classes. Production interfaces should reflect real runtime behavior, not test harness needs.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# When to Mock
|
|
2
|
+
|
|
3
|
+
Mock at **system boundaries** only:
|
|
4
|
+
|
|
5
|
+
- External APIs (payment, email, etc.)
|
|
6
|
+
- Databases (sometimes - prefer test DB)
|
|
7
|
+
- Time/randomness
|
|
8
|
+
- File system (sometimes)
|
|
9
|
+
|
|
10
|
+
Don't mock:
|
|
11
|
+
|
|
12
|
+
- Your own classes/modules
|
|
13
|
+
- Internal collaborators
|
|
14
|
+
- Anything you control
|
|
15
|
+
|
|
16
|
+
## Designing for Mockability
|
|
17
|
+
|
|
18
|
+
At system boundaries, design interfaces that are easy to mock:
|
|
19
|
+
|
|
20
|
+
**1. Use dependency injection**
|
|
21
|
+
|
|
22
|
+
Pass external dependencies in rather than creating them internally:
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
// Easy to mock
|
|
26
|
+
function processPayment(order, paymentClient) {
|
|
27
|
+
return paymentClient.charge(order.total);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Hard to mock
|
|
31
|
+
function processPayment(order) {
|
|
32
|
+
const client = new StripeClient(process.env.STRIPE_KEY);
|
|
33
|
+
return client.charge(order.total);
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**2. Prefer SDK-style interfaces over generic fetchers**
|
|
38
|
+
|
|
39
|
+
Create specific functions for each external operation instead of one generic function with conditional logic:
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
// GOOD: Each function is independently mockable
|
|
43
|
+
const api = {
|
|
44
|
+
getUser: (id) => fetch(`/users/${id}`),
|
|
45
|
+
getOrders: (userId) => fetch(`/users/${userId}/orders`),
|
|
46
|
+
createOrder: (data) => fetch('/orders', { method: 'POST', body: data }),
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// BAD: Mocking requires conditional logic inside the mock
|
|
50
|
+
const api = {
|
|
51
|
+
fetch: (endpoint, options) => fetch(endpoint, options),
|
|
52
|
+
};
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The SDK approach means:
|
|
56
|
+
|
|
57
|
+
- Each mock returns one specific shape
|
|
58
|
+
- No conditional logic in test setup
|
|
59
|
+
- Easier to see which endpoints a test exercises
|
|
60
|
+
- Type safety per endpoint
|
|
61
|
+
|
|
62
|
+
## Mock Faithfully
|
|
63
|
+
|
|
64
|
+
When a boundary must be mocked, preserve the parts of reality the test depends on:
|
|
65
|
+
|
|
66
|
+
- Include the full response shape that downstream code relies on, not just the fields used in the immediate assertion
|
|
67
|
+
- Avoid mocking away side effects the behavior under test actually needs
|
|
68
|
+
- If unsure what must remain real, run the test against the real path first and then mock the lowest external boundary
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Refactor Candidates
|
|
2
|
+
|
|
3
|
+
After TDD cycle, look for:
|
|
4
|
+
|
|
5
|
+
- **Duplication** → Extract function/class
|
|
6
|
+
- **Long methods** → Break into private helpers (keep tests on public interface)
|
|
7
|
+
- **Shallow modules** → Combine or deepen
|
|
8
|
+
- **Feature envy** → Move logic to where data lives
|
|
9
|
+
- **Primitive obsession** → Introduce value objects
|
|
10
|
+
- **Existing code** the new code reveals as problematic
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Good and Bad Tests
|
|
2
|
+
|
|
3
|
+
## Good Tests
|
|
4
|
+
|
|
5
|
+
**Integration-style**: Test through real interfaces, not mocks of internal parts.
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
// GOOD: Tests observable behavior
|
|
9
|
+
test("user can checkout with valid cart", async () => {
|
|
10
|
+
const cart = createCart();
|
|
11
|
+
cart.add(product);
|
|
12
|
+
const result = await checkout(cart, paymentMethod);
|
|
13
|
+
expect(result.status).toBe("confirmed");
|
|
14
|
+
});
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Characteristics:
|
|
18
|
+
|
|
19
|
+
- Tests behavior users/callers care about
|
|
20
|
+
- Uses public API only
|
|
21
|
+
- Survives internal refactors
|
|
22
|
+
- Describes WHAT, not HOW
|
|
23
|
+
- One logical assertion per test
|
|
24
|
+
|
|
25
|
+
## Bad Tests
|
|
26
|
+
|
|
27
|
+
**Implementation-detail tests**: Coupled to internal structure.
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
// BAD: Tests implementation details
|
|
31
|
+
test("checkout calls paymentService.process", async () => {
|
|
32
|
+
const mockPayment = jest.mock(paymentService);
|
|
33
|
+
await checkout(cart, payment);
|
|
34
|
+
expect(mockPayment.process).toHaveBeenCalledWith(cart.total);
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Red flags:
|
|
39
|
+
|
|
40
|
+
- Mocking internal collaborators
|
|
41
|
+
- Testing private methods
|
|
42
|
+
- Asserting on call counts/order
|
|
43
|
+
- Test breaks when refactoring without behavior change
|
|
44
|
+
- Test name describes HOW not WHAT
|
|
45
|
+
- Verifying through external means instead of interface
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
// BAD: Bypasses interface to verify
|
|
49
|
+
test("createUser saves to database", async () => {
|
|
50
|
+
await createUser({ name: "Alice" });
|
|
51
|
+
const row = await db.query("SELECT * FROM users WHERE name = ?", ["Alice"]);
|
|
52
|
+
expect(row).toBeDefined();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// GOOD: Verifies through interface
|
|
56
|
+
test("createUser makes user retrievable", async () => {
|
|
57
|
+
const user = await createUser({ name: "Alice" });
|
|
58
|
+
const retrieved = await getUser(user.id);
|
|
59
|
+
expect(retrieved.name).toBe("Alice");
|
|
60
|
+
});
|
|
61
|
+
```
|