@reldens/skills 0.46.0 → 0.48.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.
Files changed (40) hide show
  1. package/.claude/architecture.md +472 -0
  2. package/.claude/class-hierarchy.md +982 -0
  3. package/.claude/event-system-architecture.md +475 -0
  4. package/.claude/level-progression.md +1259 -0
  5. package/.claude/skill-execution-flow.md +979 -0
  6. package/.claude/testing-guide.md +356 -0
  7. package/.claude/testing-patterns.md +1096 -0
  8. package/CLAUDE.md +164 -29
  9. package/lib/class-path.js +13 -10
  10. package/lib/client/receiver.js +1 -3
  11. package/lib/levels-set.js +24 -17
  12. package/lib/server/sender.js +1 -1
  13. package/lib/skill.js +19 -16
  14. package/lib/types/attack.js +28 -11
  15. package/lib/types/effect.js +10 -4
  16. package/lib/types/physical-attack.js +2 -2
  17. package/lib/types/physical-effect.js +2 -2
  18. package/lib/types/physical-properties-validator.js +1 -1
  19. package/lib/types/physical-skill-runner.js +5 -5
  20. package/package.json +9 -3
  21. package/tests/fixtures/levels/base-levels.js +89 -0
  22. package/tests/fixtures/mocks/mock-client.js +44 -0
  23. package/tests/fixtures/mocks/mock-owner.js +60 -0
  24. package/tests/fixtures/mocks/mock-target.js +50 -0
  25. package/tests/fixtures/skills/base-skills.js +80 -0
  26. package/tests/run-tests.js +88 -0
  27. package/tests/unit/client/test-receiver.js +249 -0
  28. package/tests/unit/server/test-sender.js +527 -0
  29. package/tests/unit/test-class-path.js +1239 -0
  30. package/tests/unit/test-level.js +176 -0
  31. package/tests/unit/test-levels-set.js +1227 -0
  32. package/tests/unit/test-server.js +266 -0
  33. package/tests/unit/test-skill.js +1302 -0
  34. package/tests/unit/types/test-attack.js +1195 -0
  35. package/tests/unit/types/test-effect.js +587 -0
  36. package/tests/unit/types/test-physical-attack.js +564 -0
  37. package/tests/unit/types/test-physical-effect.js +769 -0
  38. package/tests/unit/types/test-physical-properties-validator.js +203 -0
  39. package/tests/unit/types/test-physical-skill-runner.js +348 -0
  40. package/tests/utils/test-helpers.js +122 -0
@@ -0,0 +1,1096 @@
1
+ # TESTING PATTERNS AND BEST PRACTICES
2
+ ## Lessons Learned from @reldens/skills Test Suite
3
+
4
+ ---
5
+
6
+ ## OVERVIEW
7
+
8
+ This document captures critical testing patterns, anti-patterns, and best practices learned from debugging and fixing the @reldens/skills test suite. These patterns apply to any event-driven system using EventsManagerSingleton.
9
+
10
+ ---
11
+
12
+ ## CRITICAL RULES
13
+
14
+ ### Rule #1: NEVER Test Through Events Unless Testing the Event System Itself
15
+
16
+ **Why:** Event firing is asynchronous and creates race conditions that make tests non-deterministic.
17
+
18
+ **❌ ANTI-PATTERN:**
19
+ ```javascript
20
+ it('should send level up message to client', async () => {
21
+ let sender = new Sender(classPath, mockClient);
22
+ sender.registerListeners(); // Registers event listener
23
+
24
+ // This fires LEVEL_UP event asynchronously
25
+ await classPath.levelUp();
26
+
27
+ // Race condition! Event listener may not have completed yet
28
+ assert.strictEqual(mockClient.sentMessages.length, 1); // ❌ May fail randomly
29
+ });
30
+ ```
31
+
32
+ **✅ CORRECT PATTERN:**
33
+ ```javascript
34
+ it('should send level up message to client', async () => {
35
+ let sender = new Sender(classPath, mockClient);
36
+ sender.registerListeners();
37
+
38
+ // Call the method directly, bypassing event system
39
+ await sender.sendLevelUpData(classPath);
40
+
41
+ // Deterministic - method has completed before assertion
42
+ assert.strictEqual(mockClient.sentMessages.length, 1); // ✓ Always works
43
+ });
44
+ ```
45
+
46
+ **When to Test Through Events:**
47
+ - When explicitly testing event firing/listening behavior
48
+ - When testing event parameter passing
49
+ - When testing event sequence/order
50
+
51
+ **Example of Valid Event Testing:**
52
+ ```javascript
53
+ it('should fire LEVEL_UP event with correct parameters', async () => {
54
+ let eventFired = false;
55
+ let receivedClassPath = null;
56
+
57
+ classPath.listenEvent(SkillsEvents.LEVEL_UP, (cp) => {
58
+ eventFired = true;
59
+ receivedClassPath = cp;
60
+ }, 'test-level-up-event');
61
+
62
+ await classPath.levelUp();
63
+
64
+ assert.strictEqual(eventFired, true);
65
+ assert.strictEqual(receivedClassPath, classPath);
66
+ });
67
+ ```
68
+
69
+ ---
70
+
71
+ ### Rule #2: NEVER Use sleep() to Fix Race Conditions
72
+
73
+ **Why:** sleep() is a band-aid that masks the real problem. Tests should be deterministic, not time-dependent.
74
+
75
+ **❌ ANTI-PATTERN:**
76
+ ```javascript
77
+ it('should update client after skill execution', async () => {
78
+ await skill.execute(target);
79
+ await TestHelpers.sleep(10); // ❌ Waiting for async event to complete
80
+ assert.strictEqual(mockClient.updated, true); // Flaky test
81
+ });
82
+ ```
83
+
84
+ **✅ CORRECT PATTERN:**
85
+ ```javascript
86
+ it('should update client after skill execution', async () => {
87
+ await sender.sendSkillExecutionData(skill, target); // Direct method call
88
+ assert.strictEqual(mockClient.updated, true); // Deterministic
89
+ });
90
+ ```
91
+
92
+ **When sleep() IS Appropriate:**
93
+ ```javascript
94
+ it('should restore canActivate after skillDelay', async () => {
95
+ let skill = new Skill({
96
+ owner: mockOwner,
97
+ skillDelay: 100 // Actual timer feature
98
+ });
99
+
100
+ skill.validate();
101
+ assert.strictEqual(skill.canActivate, false);
102
+
103
+ // ✓ Testing actual timer behavior
104
+ await TestHelpers.sleep(150);
105
+
106
+ assert.strictEqual(skill.canActivate, true);
107
+ });
108
+ ```
109
+
110
+ **Summary:**
111
+ - ❌ Don't use sleep() to wait for async events
112
+ - ✓ Do use sleep() to test actual timer/delay features (skillDelay, castTime)
113
+
114
+ ---
115
+
116
+ ### Rule #3: ALWAYS Use Unique removeKeys
117
+
118
+ **Why:** EventsManagerSingleton maintains a GLOBAL removeKey registry that persists across tests even after `clearEventListeners()`.
119
+
120
+ **❌ ANTI-PATTERN:**
121
+ ```javascript
122
+ // test-class-path.js
123
+ describe('ClassPath Events', () => {
124
+ afterEach(async () => {
125
+ await TestHelpers.clearEventListeners();
126
+ });
127
+
128
+ it('should fire ADD_SKILLS events', async () => {
129
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'before-listener');
130
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_AFTER, callback, 'after-listener');
131
+ // Test passes
132
+ });
133
+
134
+ it('should fire REMOVE_SKILLS events', async () => {
135
+ // ❌ removeKey collision! 'before-listener' already exists in global registry
136
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'before-listener');
137
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_AFTER, callback, 'after-listener');
138
+ // Listeners silently fail to register - test fails
139
+ });
140
+ });
141
+ ```
142
+
143
+ **✅ CORRECT PATTERN:**
144
+ ```javascript
145
+ describe('ClassPath Events', () => {
146
+ afterEach(async () => {
147
+ await TestHelpers.clearEventListeners();
148
+ });
149
+
150
+ it('should fire ADD_SKILLS events', async () => {
151
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_BEFORE, callback, 'add-before-listener');
152
+ classPath.listenEvent(SkillsEvents.ADD_SKILLS_AFTER, callback, 'add-after-listener');
153
+ // Test passes
154
+ });
155
+
156
+ it('should fire REMOVE_SKILLS events', async () => {
157
+ // ✓ Unique removeKeys
158
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_BEFORE, callback, 'remove-before-listener');
159
+ classPath.listenEvent(SkillsEvents.REMOVE_SKILLS_AFTER, callback, 'remove-after-listener');
160
+ // Listeners register correctly - test passes
161
+ });
162
+ });
163
+ ```
164
+
165
+ **Best Practice - Use Descriptive, Namespaced removeKeys:**
166
+ ```javascript
167
+ // Pattern: {test-suite}.{test-name}.{event-name}.{listener-purpose}
168
+ classPath.listenEvent(
169
+ SkillsEvents.LEVEL_UP,
170
+ callback,
171
+ 'class-path.level-progression.level-up.verify-label-change'
172
+ );
173
+ ```
174
+
175
+ ---
176
+
177
+ ### Rule #4: ALWAYS Clear Event Listeners in afterEach
178
+
179
+ **Why:** Event listeners persist across tests and can cause unexpected side effects.
180
+
181
+ **❌ ANTI-PATTERN:**
182
+ ```javascript
183
+ describe('Skill Events', () => {
184
+ it('test 1', async () => {
185
+ skill.listenEvent(SkillsEvents.SKILL_AFTER_EXECUTE, callback, 'listener-1');
186
+ // Test completes, listener still registered
187
+ });
188
+
189
+ it('test 2', async () => {
190
+ await skill.execute(target);
191
+ // ❌ Listener from test 1 still fires! Unexpected callback execution
192
+ });
193
+ });
194
+ ```
195
+
196
+ **✅ CORRECT PATTERN:**
197
+ ```javascript
198
+ describe('Skill Events', () => {
199
+ afterEach(async () => {
200
+ await TestHelpers.clearEventListeners();
201
+ });
202
+
203
+ it('test 1', async () => {
204
+ skill.listenEvent(SkillsEvents.SKILL_AFTER_EXECUTE, callback, 'listener-1');
205
+ // Test completes
206
+ });
207
+ // afterEach clears listeners
208
+
209
+ it('test 2', async () => {
210
+ await skill.execute(target);
211
+ // ✓ No listeners from test 1
212
+ });
213
+ });
214
+ ```
215
+
216
+ **TestHelpers.clearEventListeners() Implementation:**
217
+ ```javascript
218
+ // tests/utils/test-helpers.js
219
+ static async clearEventListeners()
220
+ {
221
+ await EventsManagerSingleton.removeAllListeners();
222
+ }
223
+ ```
224
+
225
+ **Important Note:**
226
+ - `clearEventListeners()` removes listener registrations
227
+ - It does NOT clear the removeKey registry
228
+ - This is why unique removeKeys are critical
229
+
230
+ ---
231
+
232
+ ### Rule #5: Test State Changes, Not Internal Implementation
233
+
234
+ **Why:** Tests should verify behavior and outcomes, not implementation details.
235
+
236
+ **❌ ANTI-PATTERN:**
237
+ ```javascript
238
+ it('should call applyModifiers internally', async () => {
239
+ let applyModifiersCalled = false;
240
+ let originalMethod = skill.applyModifiers;
241
+ skill.applyModifiers = function(...args) {
242
+ applyModifiersCalled = true;
243
+ return originalMethod.apply(this, args);
244
+ };
245
+
246
+ await skill.execute(target);
247
+
248
+ assert.strictEqual(applyModifiersCalled, true); // ❌ Testing implementation
249
+ });
250
+ ```
251
+
252
+ **✅ CORRECT PATTERN:**
253
+ ```javascript
254
+ it('should apply target effects to target', async () => {
255
+ let initialValue = mockTarget.stats.hp;
256
+ let modifier = new Modifier({
257
+ key: 'hp-buff',
258
+ propertyKey: 'stats.hp',
259
+ operation: '+',
260
+ value: 20
261
+ });
262
+ let skill = new Effect({
263
+ owner: mockOwner,
264
+ targetEffects: [modifier]
265
+ });
266
+
267
+ await skill.execute(mockTarget);
268
+
269
+ // ✓ Testing observable behavior
270
+ assert.strictEqual(mockTarget.stats.hp, initialValue + 20);
271
+ });
272
+ ```
273
+
274
+ ---
275
+
276
+ ### Rule #6: Use Fixtures for Consistent Test Data
277
+
278
+ **Why:** Reduces duplication, ensures consistency, makes tests easier to maintain.
279
+
280
+ **❌ ANTI-PATTERN:**
281
+ ```javascript
282
+ it('test 1', async () => {
283
+ let skill = new Attack({
284
+ key: 'sword-attack',
285
+ owner: mockOwner,
286
+ hitDamage: 50,
287
+ attackProperties: ['atk'],
288
+ defenseProperties: ['def']
289
+ });
290
+ // Use skill
291
+ });
292
+
293
+ it('test 2', async () => {
294
+ // ❌ Duplicate skill creation with slightly different values
295
+ let skill = new Attack({
296
+ key: 'sword-attack',
297
+ owner: mockOwner,
298
+ hitDamage: 45, // Oops, different damage
299
+ attackProperties: ['atk'],
300
+ defenseProperties: ['def']
301
+ });
302
+ // Use skill
303
+ });
304
+ ```
305
+
306
+ **✅ CORRECT PATTERN:**
307
+ ```javascript
308
+ // tests/fixtures/skills/attack-skills.js
309
+ export const basicSwordAttack = {
310
+ key: 'sword-attack',
311
+ hitDamage: 50,
312
+ attackProperties: ['atk'],
313
+ defenseProperties: ['def'],
314
+ affectedProperty: 'hp'
315
+ };
316
+
317
+ // tests/unit/types/test-attack.js
318
+ import { basicSwordAttack } from '../../fixtures/skills/attack-skills.js';
319
+
320
+ it('test 1', async () => {
321
+ let skill = new Attack({
322
+ ...basicSwordAttack,
323
+ owner: mockOwner
324
+ });
325
+ // Use skill
326
+ });
327
+
328
+ it('test 2', async () => {
329
+ let skill = new Attack({
330
+ ...basicSwordAttack,
331
+ owner: mockOwner
332
+ });
333
+ // ✓ Consistent skill data
334
+ });
335
+ ```
336
+
337
+ ---
338
+
339
+ ### Rule #7: Mock External Dependencies
340
+
341
+ **Why:** Unit tests should be isolated from external systems (network, database, physics engine).
342
+
343
+ **❌ ANTI-PATTERN:**
344
+ ```javascript
345
+ it('should execute physical skill', async () => {
346
+ let physicsEngine = new RealPhysicsEngine(); // ❌ Real physics engine
347
+ let owner = new Player({physicsEngine});
348
+ let skill = new PhysicalAttack({owner});
349
+
350
+ await skill.execute(target); // Depends on real physics simulation
351
+ });
352
+ ```
353
+
354
+ **✅ CORRECT PATTERN:**
355
+ ```javascript
356
+ it('should execute physical skill', async () => {
357
+ let mockOwner = new MockOwner();
358
+ mockOwner.executePhysicalSkill = async (target, skill, executeOnHit) => {
359
+ // ✓ Mock physics behavior
360
+ await executeOnHit(target);
361
+ return true;
362
+ };
363
+
364
+ let skill = new PhysicalAttack({
365
+ owner: mockOwner,
366
+ objectWidth: 10,
367
+ objectHeight: 10
368
+ });
369
+
370
+ await skill.execute(mockTarget);
371
+ // Deterministic, fast, isolated
372
+ });
373
+ ```
374
+
375
+ **Mock Classes in @reldens/skills:**
376
+ - `MockOwner` - Mock entity with position methods
377
+ - `MockTarget` - Mock target with stats
378
+ - `MockClient` - Mock network client with send/broadcast
379
+
380
+ ---
381
+
382
+ ### Rule #8: Test Edge Cases and Boundary Conditions
383
+
384
+ **Why:** Edge cases reveal bugs that normal cases don't.
385
+
386
+ **Examples:**
387
+
388
+ **Boundary Values:**
389
+ ```javascript
390
+ it('should handle 0 damage', async () => {
391
+ let skill = new Attack({
392
+ owner: mockOwner,
393
+ hitDamage: 0
394
+ });
395
+ await skill.execute(mockTarget);
396
+ // Verify behavior with zero damage
397
+ });
398
+
399
+ it('should handle infinite range', async () => {
400
+ let skill = new Skill({
401
+ owner: mockOwner,
402
+ range: 0 // 0 = infinite range
403
+ });
404
+ assert.strictEqual(skill.owner.isInRange(skill, farAwayTarget, skill.range), true);
405
+ });
406
+ ```
407
+
408
+ **Null/Undefined:**
409
+ ```javascript
410
+ it('should handle undefined target', async () => {
411
+ let skill = new Effect({owner: mockOwner});
412
+ let result = await skill.execute(undefined);
413
+ assert.strictEqual(result.error, SKILL.TARGET_NOT_AVAILABLE);
414
+ });
415
+ ```
416
+
417
+ **Empty Collections:**
418
+ ```javascript
419
+ it('should handle empty ownerEffects', async () => {
420
+ let skill = new Skill({
421
+ owner: mockOwner,
422
+ ownerEffects: []
423
+ });
424
+ await skill.execute(mockTarget);
425
+ // Should not throw, should skip effects application
426
+ });
427
+ ```
428
+
429
+ **Maximum Values:**
430
+ ```javascript
431
+ it('should not allow damage below 0 when allowEffectBelowZero is false', async () => {
432
+ mockTarget.stats.hp = 50;
433
+ let skill = new Attack({
434
+ owner: mockOwner,
435
+ hitDamage: 100,
436
+ allowEffectBelowZero: false
437
+ });
438
+ await skill.execute(mockTarget);
439
+ assert.strictEqual(mockTarget.stats.hp, 0); // Clamped to 0
440
+ });
441
+ ```
442
+
443
+ ---
444
+
445
+ ### Rule #9: Use Descriptive Test Names
446
+
447
+ **Why:** Test names should describe what is being tested and expected outcome.
448
+
449
+ **❌ ANTI-PATTERN:**
450
+ ```javascript
451
+ it('test 1', async () => {
452
+ // What does this test?
453
+ });
454
+
455
+ it('attack works', async () => {
456
+ // Too vague
457
+ });
458
+
459
+ it('check dodge', async () => {
460
+ // Unclear expectation
461
+ });
462
+ ```
463
+
464
+ **✅ CORRECT PATTERN:**
465
+ ```javascript
466
+ it('should apply damage to target hp when attack succeeds', async () => {
467
+ // Clear: what, when, expected outcome
468
+ });
469
+
470
+ it('should return DODGED error when target dodge > aim * dodgeOverAimSuccess', async () => {
471
+ // Clear: condition and expected result
472
+ });
473
+
474
+ it('should apply critical damage multiplier when critical roll succeeds', async () => {
475
+ // Clear: feature and expected behavior
476
+ });
477
+ ```
478
+
479
+ **Pattern:**
480
+ ```
481
+ should [action/behavior] when [condition]
482
+ should [expected outcome] [optional: given specific input]
483
+ ```
484
+
485
+ ---
486
+
487
+ ### Rule #10: One Assertion Per Logical Concept
488
+
489
+ **Why:** Multiple unrelated assertions make it hard to identify what failed.
490
+
491
+ **❌ ANTI-PATTERN:**
492
+ ```javascript
493
+ it('should execute skill correctly', async () => {
494
+ await skill.execute(target);
495
+ assert.strictEqual(skill.usesCount, 1); // Tests usage tracking
496
+ assert.strictEqual(target.stats.hp, 80); // Tests damage application
497
+ assert.strictEqual(skill.canActivate, false); // Tests cooldown
498
+ assert.strictEqual(mockClient.messagesSent.length, 1); // Tests networking
499
+ // If this fails, which assertion failed? What broke?
500
+ });
501
+ ```
502
+
503
+ **✅ CORRECT PATTERN:**
504
+ ```javascript
505
+ describe('Skill execution', () => {
506
+ it('should increment usesCount after execution', async () => {
507
+ await skill.execute(target);
508
+ assert.strictEqual(skill.usesCount, 1);
509
+ });
510
+
511
+ it('should apply damage to target hp', async () => {
512
+ let initialHp = target.stats.hp;
513
+ await skill.execute(target);
514
+ assert.strictEqual(target.stats.hp, initialHp - skill.hitDamage);
515
+ });
516
+
517
+ it('should set canActivate to false during cooldown', async () => {
518
+ await skill.execute(target);
519
+ assert.strictEqual(skill.canActivate, false);
520
+ });
521
+
522
+ it('should send execution message to client', async () => {
523
+ await sender.sendSkillExecutionData(skill, target);
524
+ assert.strictEqual(mockClient.messagesSent.length, 1);
525
+ });
526
+ });
527
+ ```
528
+
529
+ **Exception - Related Assertions:**
530
+ ```javascript
531
+ it('should calculate damage correctly with attack and defense', async () => {
532
+ mockOwner.atk = 100;
533
+ mockTarget.def = 50;
534
+ let result = await skill.execute(mockTarget);
535
+
536
+ // These are all related to damage calculation
537
+ assert.ok(result.damages);
538
+ assert.ok(result.damages.hp);
539
+ assert.strictEqual(typeof result.damages.hp, 'number');
540
+ assert.ok(result.damages.hp > 0);
541
+ });
542
+ ```
543
+
544
+ ---
545
+
546
+ ## COMMON TESTING ANTI-PATTERNS
547
+
548
+ ### Anti-Pattern #1: Testing Private Methods
549
+
550
+ **❌ DON'T:**
551
+ ```javascript
552
+ it('should call private _calculateDamage method', async () => {
553
+ let damage = skill._calculateDamage(target);
554
+ assert.ok(damage > 0);
555
+ });
556
+ ```
557
+
558
+ **✅ DO:**
559
+ ```javascript
560
+ it('should apply calculated damage to target', async () => {
561
+ let initialHp = target.stats.hp;
562
+ await skill.execute(target);
563
+ assert.ok(target.stats.hp < initialHp);
564
+ });
565
+ ```
566
+
567
+ ---
568
+
569
+ ### Anti-Pattern #2: Over-Mocking
570
+
571
+ **❌ DON'T:**
572
+ ```javascript
573
+ it('should execute skill', async () => {
574
+ // Mocking everything - not testing real behavior
575
+ skill.validate = () => true;
576
+ skill.runSkillLogic = () => ({success: true});
577
+ skill.fireEvent = () => {};
578
+
579
+ let result = await skill.execute(target);
580
+ assert.strictEqual(result.success, true); // Not testing anything real
581
+ });
582
+ ```
583
+
584
+ **✅ DO:**
585
+ ```javascript
586
+ it('should execute skill', async () => {
587
+ // Only mock external dependencies
588
+ let skill = new Attack({
589
+ owner: mockOwner, // Mock
590
+ hitDamage: 50
591
+ });
592
+
593
+ let result = await skill.execute(mockTarget); // Real execution
594
+ assert.ok(result.damages); // Real result
595
+ });
596
+ ```
597
+
598
+ ---
599
+
600
+ ### Anti-Pattern #3: Testing Framework Code
601
+
602
+ **❌ DON'T:**
603
+ ```javascript
604
+ it('should fire event through EventsManager', async () => {
605
+ let eventFired = false;
606
+ EventsManagerSingleton.on('test.event', () => {
607
+ eventFired = true;
608
+ });
609
+
610
+ await EventsManagerSingleton.emit('test.event');
611
+ assert.strictEqual(eventFired, true); // Testing EventsManager, not your code
612
+ });
613
+ ```
614
+
615
+ **✅ DO:**
616
+ ```javascript
617
+ it('should fire LEVEL_UP event when leveling up', async () => {
618
+ let eventFired = false;
619
+ classPath.listenEvent(SkillsEvents.LEVEL_UP, () => {
620
+ eventFired = true;
621
+ }, 'test-level-up');
622
+
623
+ await classPath.levelUp(); // Testing your code
624
+ assert.strictEqual(eventFired, true);
625
+ });
626
+ ```
627
+
628
+ ---
629
+
630
+ ### Anti-Pattern #4: Assertion-less Tests
631
+
632
+ **❌ DON'T:**
633
+ ```javascript
634
+ it('should execute skill without errors', async () => {
635
+ await skill.execute(target);
636
+ // No assertions - test passes even if skill is broken
637
+ });
638
+ ```
639
+
640
+ **✅ DO:**
641
+ ```javascript
642
+ it('should execute skill without errors', async () => {
643
+ let result = await skill.execute(target);
644
+ assert.ok(result); // At minimum, verify result exists
645
+ assert.strictEqual(result.error, undefined); // Verify no error
646
+ });
647
+ ```
648
+
649
+ ---
650
+
651
+ ### Anti-Pattern #5: Dependent Tests
652
+
653
+ **❌ DON'T:**
654
+ ```javascript
655
+ let sharedSkill;
656
+
657
+ it('test 1 - create skill', async () => {
658
+ sharedSkill = new Skill({owner: mockOwner});
659
+ });
660
+
661
+ it('test 2 - use skill', async () => {
662
+ // ❌ Depends on test 1 running first
663
+ await sharedSkill.execute(target);
664
+ });
665
+ ```
666
+
667
+ **✅ DO:**
668
+ ```javascript
669
+ it('test 1 - create skill', async () => {
670
+ let skill = new Skill({owner: mockOwner});
671
+ // Test skill creation
672
+ });
673
+
674
+ it('test 2 - use skill', async () => {
675
+ let skill = new Skill({owner: mockOwner}); // ✓ Independent
676
+ await skill.execute(target);
677
+ });
678
+ ```
679
+
680
+ ---
681
+
682
+ ## PROVEN TESTING PATTERNS
683
+
684
+ ### Pattern #1: Arrange-Act-Assert (AAA)
685
+
686
+ ```javascript
687
+ it('should apply damage to target hp', async () => {
688
+ // ARRANGE - Set up test data
689
+ let initialHp = mockTarget.stats.hp;
690
+ let skill = new Attack({
691
+ owner: mockOwner,
692
+ hitDamage: 50,
693
+ affectedProperty: 'hp'
694
+ });
695
+
696
+ // ACT - Execute the behavior
697
+ await skill.execute(mockTarget);
698
+
699
+ // ASSERT - Verify the outcome
700
+ assert.strictEqual(mockTarget.stats.hp, initialHp - 50);
701
+ });
702
+ ```
703
+
704
+ ---
705
+
706
+ ### Pattern #2: Setup and Teardown
707
+
708
+ ```javascript
709
+ describe('Attack Skills', () => {
710
+ let mockOwner, mockTarget, skill;
711
+
712
+ beforeEach(() => {
713
+ // SETUP - Run before each test
714
+ mockOwner = new MockOwner();
715
+ mockTarget = new MockTarget();
716
+ skill = new Attack({
717
+ owner: mockOwner,
718
+ hitDamage: 50
719
+ });
720
+ });
721
+
722
+ afterEach(async () => {
723
+ // TEARDOWN - Clean up after each test
724
+ await TestHelpers.clearEventListeners();
725
+ });
726
+
727
+ it('test 1', async () => {
728
+ // Use fresh instances
729
+ });
730
+
731
+ it('test 2', async () => {
732
+ // Use fresh instances
733
+ });
734
+ });
735
+ ```
736
+
737
+ ---
738
+
739
+ ### Pattern #3: Parameterized Tests
740
+
741
+ ```javascript
742
+ describe('Damage calculation with various stats', () => {
743
+ const testCases = [
744
+ {atk: 100, def: 0, expectedDamage: 50},
745
+ {atk: 100, def: 50, expectedDamage: 25},
746
+ {atk: 100, def: 100, expectedDamage: 0},
747
+ {atk: 50, def: 100, expectedDamage: 0}
748
+ ];
749
+
750
+ testCases.forEach(({atk, def, expectedDamage}) => {
751
+ it(`should deal ${expectedDamage} damage when atk=${atk} and def=${def}`, async () => {
752
+ mockOwner.atk = atk;
753
+ mockTarget.def = def;
754
+ let skill = new Attack({
755
+ owner: mockOwner,
756
+ hitDamage: 50,
757
+ attackProperties: ['atk'],
758
+ defenseProperties: ['def']
759
+ });
760
+
761
+ let result = await skill.execute(mockTarget);
762
+
763
+ assert.strictEqual(result.damages.hp, expectedDamage);
764
+ });
765
+ });
766
+ });
767
+ ```
768
+
769
+ ---
770
+
771
+ ### Pattern #4: Test Doubles (Mock, Stub, Spy)
772
+
773
+ **Mock - Verify interaction:**
774
+ ```javascript
775
+ it('should call executePhysicalSkill on owner', async () => {
776
+ let called = false;
777
+ let receivedTarget = null;
778
+
779
+ mockOwner.executePhysicalSkill = async (target, skill, callback) => {
780
+ called = true;
781
+ receivedTarget = target;
782
+ await callback(target);
783
+ };
784
+
785
+ let skill = new PhysicalAttack({
786
+ owner: mockOwner,
787
+ objectWidth: 10,
788
+ objectHeight: 10
789
+ });
790
+
791
+ await skill.execute(mockTarget);
792
+
793
+ assert.strictEqual(called, true);
794
+ assert.strictEqual(receivedTarget, mockTarget);
795
+ });
796
+ ```
797
+
798
+ **Stub - Provide controlled response:**
799
+ ```javascript
800
+ it('should handle out of range result', async () => {
801
+ mockOwner.isInRange = () => false; // Stub returns false
802
+
803
+ let skill = new Skill({
804
+ owner: mockOwner,
805
+ range: 100,
806
+ rangeAutomaticValidation: true
807
+ });
808
+
809
+ let result = skill.validate();
810
+
811
+ assert.strictEqual(result, false);
812
+ });
813
+ ```
814
+
815
+ **Spy - Track calls:**
816
+ ```javascript
817
+ it('should fire event multiple times', async () => {
818
+ let callCount = 0;
819
+ let receivedArgs = [];
820
+
821
+ skill.listenEvent(SkillsEvents.SKILL_AFTER_EXECUTE, (...args) => {
822
+ callCount++;
823
+ receivedArgs.push(args);
824
+ }, 'spy-listener');
825
+
826
+ await skill.execute(target1);
827
+ await skill.execute(target2);
828
+
829
+ assert.strictEqual(callCount, 2);
830
+ assert.strictEqual(receivedArgs.length, 2);
831
+ });
832
+ ```
833
+
834
+ ---
835
+
836
+ ### Pattern #5: Error Testing
837
+
838
+ ```javascript
839
+ it('should return error when target is out of range', async () => {
840
+ mockOwner.isInRange = () => false;
841
+
842
+ let skill = new Effect({
843
+ owner: mockOwner,
844
+ range: 100,
845
+ rangeAutomaticValidation: true
846
+ });
847
+
848
+ let result = await skill.execute(mockTarget);
849
+
850
+ assert.strictEqual(result.error, SKILL.OUT_OF_RANGE);
851
+ });
852
+
853
+ it('should return error when owner is casting', async () => {
854
+ mockOwner.isCasting = true;
855
+
856
+ let skill = new Skill({owner: mockOwner});
857
+ let result = await skill.execute(mockTarget);
858
+
859
+ assert.strictEqual(result.error, SKILL.CAN_NOT_ACTIVATE);
860
+ });
861
+ ```
862
+
863
+ ---
864
+
865
+ ## BUG DISCOVERY PATTERNS
866
+
867
+ ### Pattern: Proof Before Fix
868
+
869
+ **Process:**
870
+ 1. Identify failing test
871
+ 2. Read production code completely
872
+ 3. Trace execution flow with debugger/logs
873
+ 4. Find exact line causing issue
874
+ 5. Understand why it's wrong
875
+ 6. Provide proof (comparison to correct code, specification)
876
+ 7. Apply fix
877
+ 8. Verify fix resolves issue
878
+
879
+ **Example from Session:**
880
+
881
+ **Bug:** Skill.applyModifiers() applying critical to wrong value
882
+
883
+ **Proof Process:**
884
+ 1. Test showed: Expected 100, got 120 (with 2x critical)
885
+ 2. Read lib/skill.js:293-309 completely
886
+ 3. Traced: modifier.value = 10, current = 80, critical = 2x
887
+ 4. Found bug at line 307:
888
+ ```javascript
889
+ newValue = this.applyCriticalValue(newValue); // Applies to (80+10)=90
890
+ ```
891
+ 5. Compared to Attack.js:101 (correct pattern):
892
+ ```javascript
893
+ damage = damage + this.getCriticalDiff(damage); // Applies to damage only
894
+ ```
895
+ 6. Proof: Attack applies critical to damage value only, Effect was applying to sum
896
+ 7. Applied fix using getCriticalDiff()
897
+ 8. Test passed: 80 + (10*2) = 100 ✓
898
+
899
+ ---
900
+
901
+ ### Pattern: Explore Don't Guess
902
+
903
+ **❌ DON'T:**
904
+ ```javascript
905
+ // Test is failing, let me try:
906
+ await TestHelpers.sleep(10); // Maybe timing issue?
907
+ // Still failing, let me try:
908
+ classPath.listenEvent(..., 'different-key'); // Maybe key issue?
909
+ // Still failing, let me try:
910
+ await classPath.levelUp(); await classPath.levelUp(); // Call twice?
911
+ // ❌ Guessing randomly
912
+ ```
913
+
914
+ **✅ DO:**
915
+ ```javascript
916
+ // Test is failing
917
+ // 1. Read the test completely
918
+ // 2. Read the production code completely
919
+ // 3. Add logging to trace execution
920
+ // 4. Find WHERE it fails
921
+ // 5. Find WHY it fails
922
+ // 6. Prove the root cause
923
+ // 7. Apply targeted fix
924
+ ```
925
+
926
+ **Example from Session:**
927
+
928
+ **Issue:** REMOVE_SKILLS event listeners not firing
929
+
930
+ **Exploration:**
931
+ 1. Read test completely - sees listeners registered, event fired, but flags stay false
932
+ 2. Read ClassPath.listenEvent() - calls events.onWithKey()
933
+ 3. Read EventsManagerSingleton - found removeKey registry
934
+ 4. Read clearEventListeners() - clears listeners but NOT registry
935
+ 5. Checked ADD_SKILLS test - used same removeKeys!
936
+ 6. **Proof:** removeKey registry persists, causing collision
937
+ 7. **Fix:** Use unique removeKeys
938
+
939
+ ---
940
+
941
+ ## TEST ORGANIZATION
942
+
943
+ ### File Structure:
944
+ ```
945
+ tests/
946
+ ├── run-tests.js # Test runner
947
+ ├── utils/
948
+ │ └── test-helpers.js # Shared utilities
949
+ ├── fixtures/
950
+ │ ├── mocks/ # Mock classes
951
+ │ ├── skills/ # Skill test data
952
+ │ └── levels/ # Level test data
953
+ └── unit/
954
+ ├── test-skill.js # Unit tests
955
+ ├── test-levels-set.js
956
+ ├── types/
957
+ │ ├── test-attack.js
958
+ │ └── test-effect.js
959
+ ├── server/
960
+ │ └── test-sender.js
961
+ └── client/
962
+ └── test-receiver.js
963
+ ```
964
+
965
+ ### Test File Template:
966
+ ```javascript
967
+ import {describe, it, beforeEach, afterEach} from 'node:test';
968
+ import assert from 'node:assert';
969
+ import {Skill} from '../../lib/skill.js';
970
+ import {MockOwner} from '../fixtures/mocks/mock-owner.js';
971
+ import {TestHelpers} from '../utils/test-helpers.js';
972
+
973
+ describe('Skill - Feature Description', () => {
974
+ let mockOwner, mockTarget, skill;
975
+
976
+ beforeEach(() => {
977
+ mockOwner = new MockOwner();
978
+ mockTarget = new MockTarget();
979
+ });
980
+
981
+ afterEach(async () => {
982
+ await TestHelpers.clearEventListeners();
983
+ });
984
+
985
+ describe('Sub-feature', () => {
986
+ it('should do X when Y', async () => {
987
+ // Arrange
988
+ // Act
989
+ // Assert
990
+ });
991
+ });
992
+ });
993
+ ```
994
+
995
+ ---
996
+
997
+ ## DEBUGGING CHECKLIST
998
+
999
+ When a test fails:
1000
+
1001
+ - [ ] Read the complete test code
1002
+ - [ ] Read the complete production code being tested
1003
+ - [ ] Understand what the test expects
1004
+ - [ ] Understand what the production code does
1005
+ - [ ] Add logging to trace execution
1006
+ - [ ] Identify the exact line that produces wrong result
1007
+ - [ ] Understand WHY it's wrong
1008
+ - [ ] Find proof (comparison, specification, other code)
1009
+ - [ ] Apply targeted fix
1010
+ - [ ] Verify fix works
1011
+ - [ ] Check for similar issues in other code
1012
+ - [ ] Update documentation if pattern discovered
1013
+
1014
+ **NEVER:**
1015
+ - [ ] Guess randomly
1016
+ - [ ] Try multiple fixes without understanding
1017
+ - [ ] Use sleep() to mask race conditions
1018
+ - [ ] Delete tests instead of fixing them
1019
+ - [ ] Modify tests to match broken code
1020
+
1021
+ ---
1022
+
1023
+ ## CRITICAL LESSONS FROM SESSION
1024
+
1025
+ ### Lesson #1: EventsManagerSingleton removeKey Registry Persists
1026
+
1027
+ **Discovery:** removeKey registry is NOT cleared by removeAllListeners()
1028
+
1029
+ **Impact:** Tests reusing removeKeys fail silently
1030
+
1031
+ **Solution:** Use unique removeKeys across all tests
1032
+
1033
+ **Pattern:**
1034
+ ```javascript
1035
+ '{component}.{test-suite}.{specific-test}.{event-name}'
1036
+ // Example: 'class-path.events.remove-skills.before-listener'
1037
+ ```
1038
+
1039
+ ---
1040
+
1041
+ ### Lesson #2: Critical Applies to Value Only, Not Sum
1042
+
1043
+ **Discovery:** Critical should apply to modifier/damage value, not to (current + value)
1044
+
1045
+ **Impact:** Critical damage/effects were doubled incorrectly
1046
+
1047
+ **Solution:** Use getCriticalDiff() to calculate bonus, add to result
1048
+
1049
+ **Pattern:**
1050
+ ```javascript
1051
+ let newValue = modifier.getModifiedValue(); // current + value
1052
+ newValue = newValue + this.getCriticalDiff(modifier.value); // + critical bonus
1053
+ ```
1054
+
1055
+ ---
1056
+
1057
+ ### Lesson #3: Test Methods Directly, Not Through Events
1058
+
1059
+ **Discovery:** Testing through events creates race conditions
1060
+
1061
+ **Impact:** Tests fail randomly due to timing
1062
+
1063
+ **Solution:** Call methods directly, only test events when testing event system
1064
+
1065
+ **Pattern:**
1066
+ ```javascript
1067
+ // ❌ await classPath.levelUp(); assert(client.messagesSent);
1068
+ // ✓ await sender.sendLevelUpData(classPath); assert(client.messagesSent);
1069
+ ```
1070
+
1071
+ ---
1072
+
1073
+ ### Lesson #4: sleep() is for Timers, Not Race Conditions
1074
+
1075
+ **Discovery:** sleep() masks async issues instead of fixing them
1076
+
1077
+ **Impact:** Tests become time-dependent and flaky
1078
+
1079
+ **Solution:** Fix test pattern (direct calls), only use sleep() for timer features
1080
+
1081
+ **Pattern:**
1082
+ ```javascript
1083
+ // ❌ await action(); await sleep(10); assert(result);
1084
+ // ✓ await directMethod(); assert(result);
1085
+ // ✓ skill.validate(); await sleep(skillDelay + 10); assert(canActivate);
1086
+ ```
1087
+
1088
+ ---
1089
+
1090
+ ## REFERENCES
1091
+
1092
+ - Test Runner: `tests/run-tests.js`
1093
+ - Test Helpers: `tests/utils/test-helpers.js`
1094
+ - Mock Classes: `tests/fixtures/mocks/`
1095
+ - Event System: `.claude/event-system-architecture.md`
1096
+ - Skill Execution: `.claude/skill-execution-flow.md`