-
Notifications
You must be signed in to change notification settings - Fork 282
Expand file tree
/
Copy pathrepository.test.ts
More file actions
1352 lines (1091 loc) · 44.5 KB
/
Copy pathrepository.test.ts
File metadata and controls
1352 lines (1091 loc) · 44.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Test suite for src/lib/repository.ts
*
* Covers:
* 1. Basic round-trip — write then read back for both entities.
* 2. Data isolation — contracts and milestones live under the same key but
* never clobber each other.
* 3. Corrupt data handling — malformed JSON falls back to [] gracefully.
* 4. SSR context isolation — functions return [] safely when window is absent.
* 5. Empty-store defaults — first read on a fresh store returns [].
* 6. Multiple writes — each save is additive, not a full replacement.
* 7. writeStore failure — localStorage.setItem throws; error reported, no crash.
* 8. clearAppData — removes STORAGE_KEY; SSR no-op; reporter on failure.
* 9. clearByPrefix — prefix scoping, snapshot iteration, SSR no-op, reporter
* on failure, edge-cases (no matches, mixed keys, throwing removeItem).
*/
import {
isBrowser,
listContracts,
saveContract,
upsertContract,
getContractVersion,
updateContract,
updateMilestone,
listMilestones,
saveMilestone,
deleteMilestones,
bulkUpdateMilestoneStatus,
exportMilestones,
listWalletItems,
saveWalletItem,
updateWalletItem,
deleteWalletItems,
clearAppData,
clearByPrefix,
STORAGE_KEY,
} from '../repository';
import type { Contract, Milestone } from '@/types/domain';
import { setErrorReporter } from '../errorReporter';
// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------
const contractA: Contract = {
contractName: 'Alpha Contract',
parties: [{ label: 'Client', address: '0xAAA' }],
totalValue: 1000,
currency: 'USD',
status: 'Active',
createdAt: 'Jan 1, 2025',
milestoneCount: 2,
};
const contractB: Contract = {
contractName: 'Beta Contract',
parties: [{ label: 'Freelancer', address: '0xBBB' }],
totalValue: 2500,
currency: 'USD',
status: 'Pending',
createdAt: 'Feb 1, 2025',
milestoneCount: 1,
};
const milestoneA: Milestone = {
id: 'ms-001',
title: 'Kickoff',
status: 'Pending',
payout: 500,
currency: 'USD',
dueDate: 'Mar 1, 2025',
};
const milestoneB: Milestone = {
id: 'ms-002',
title: 'Delivery',
status: 'Completed',
payout: 1500,
currency: 'USD',
dueDate: 'Apr 15, 2025',
};
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Directly seeds raw JSON into localStorage for corruption tests. */
function seedRaw(value: string) {
window.localStorage.setItem(STORAGE_KEY, value);
}
// ---------------------------------------------------------------------------
// Setup / teardown
// ---------------------------------------------------------------------------
beforeEach(() => {
window.localStorage.clear();
jest.restoreAllMocks();
});
// ===========================================================================
// 0. isBrowser SSR GUARD
// ===========================================================================
describe('isBrowser', () => {
it('returns true when window is defined (browser environment)', () => {
expect(isBrowser()).toBe(true);
});
});
// ===========================================================================
// 1. EMPTY STORE DEFAULTS
// ===========================================================================
describe('empty store', () => {
it('listContracts returns [] when storage is empty', () => {
expect(listContracts()).toEqual([]);
});
it('listMilestones returns [] when storage is empty', () => {
expect(listMilestones()).toEqual([]);
});
});
// ===========================================================================
// 2. BASIC ROUND-TRIP
// ===========================================================================
describe('contract round-trip', () => {
it('saves a contract and reads it back', () => {
saveContract(contractA);
expect(listContracts()).toEqual([contractA]);
});
it('preserves all Contract fields intact', () => {
saveContract(contractA);
const [result] = listContracts();
expect(result.contractName).toBe('Alpha Contract');
expect(result.parties).toEqual([{ label: 'Client', address: '0xAAA' }]);
expect(result.totalValue).toBe(1000);
expect(result.status).toBe('Active');
expect(result.milestoneCount).toBe(2);
});
});
describe('contract upsert', () => {
it('replaces a matching contract by contractName instead of appending a duplicate', () => {
saveContract(contractA);
const version = getContractVersion(contractA.contractName);
const updatedContract: Contract = {
...contractA,
status: 'Completed',
milestoneCount: 3,
version,
};
const result = upsertContract(updatedContract);
expect(result).toEqual({ success: true, stale: false });
expect(listContracts()[0].status).toBe('Completed');
});
it('appends the contract when no matching contractName exists yet', () => {
saveContract(contractA);
const version = getContractVersion(contractA.contractName);
const result = upsertContract({ ...contractB, version });
expect(result).toEqual({ success: true, stale: false });
expect(listContracts()).toEqual([contractA, { ...contractB, version: 1 }]);
});
it('preserves array order and does not duplicate when replacing a same-name contract in place', () => {
saveContract(contractA);
saveContract(contractB);
const version = getContractVersion(contractA.contractName);
const updatedA: Contract = {
...contractA,
status: 'Completed',
version,
};
const result = upsertContract(updatedA);
expect(result).toEqual({ success: true, stale: false });
const contracts = listContracts();
expect(contracts).toHaveLength(2);
expect(contracts[0].status).toBe('Completed');
expect(contracts[1].contractName).toBe('Beta Contract');
});
it('never disturbs persisted milestones and preserves other contracts unchanged during upsert', () => {
saveContract(contractA);
saveContract(contractB);
saveMilestone(milestoneA);
saveMilestone(milestoneB);
const version = getContractVersion(contractB.contractName);
const updatedB: Contract = {
...contractB,
status: 'Completed',
version,
};
expect(upsertContract(updatedB)).toEqual({ success: true, stale: false });
// Other contracts and milestones remain unchanged
const contracts = listContracts();
expect(contracts).toHaveLength(2);
expect(contracts[0].contractName).toBe('Alpha Contract');
expect(contracts[1].status).toBe('Completed');
expect(listMilestones()).toEqual([milestoneA, milestoneB]);
});
it('successfully inserts a contract into an empty store', () => {
// New contract — version 0 is the baseline
const result = upsertContract({ ...contractA, version: 0 });
expect(result).toEqual({ success: true, stale: false });
const contracts = listContracts();
expect(contracts).toHaveLength(1);
expect(contracts[0].contractName).toBe('Alpha Contract');
expect(contracts[0].version).toBe(1);
});
it('replaces only the first candidate and preserves array order when multiple same-name candidates exist', () => {
// Seed store with duplicate names manually
const duplicateA1 = { ...contractA, status: 'Active' as const };
const duplicateA2 = { ...contractA, status: 'Pending' as const };
const store = {
contracts: [duplicateA1, contractB, duplicateA2],
milestones: []
};
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(store));
const version = getContractVersion(contractA.contractName);
const upserted: Contract = { ...contractA, status: 'Completed' as const, version };
const result = upsertContract(upserted);
expect(result).toEqual({ success: true, stale: false });
const contracts = listContracts();
expect(contracts).toHaveLength(3);
// Only the first one is replaced, order is preserved
expect(contracts[0].status).toBe('Completed');
expect(contracts[1].contractName).toBe('Beta Contract');
expect(contracts[2].status).toBe('Pending');
});
describe('stale-overwrite guard', () => {
it('rejects the write with stale:true when the incoming version is behind the stored version', () => {
// Seed the store with an initial contract via saveContract (version 0)
saveContract(contractA);
// Advance the stored version to 1 by performing one successful upsert
upsertContract({ ...contractA, status: 'Completed', version: 0 });
// Now attempt a stale write with version 0 while the stored version is 1
const staleUpdate: Contract = {
...contractA,
status: 'Disputed',
version: 0,
};
const result = upsertContract(staleUpdate);
expect(result).toEqual({ success: false, stale: true });
// Stored contract is unchanged — still at 'Completed' from the valid upsert
expect(listContracts()[0].status).toBe('Completed');
});
it('allows the write when the incoming version matches the stored version', () => {
saveContract(contractA);
const version = getContractVersion(contractA.contractName);
const update: Contract = {
...contractA,
status: 'Completed',
version,
};
expect(upsertContract(update)).toEqual({ success: true, stale: false });
expect(listContracts()[0].status).toBe('Completed');
});
it('allows the write when no stored contract exists yet (version 0)', () => {
const result = upsertContract({ ...contractA, version: 0 });
expect(result).toEqual({ success: true, stale: false });
});
it('increments the version on each successful upsert', () => {
saveContract(contractA);
const v1 = getContractVersion(contractA.contractName);
expect(v1).toBe(0);
const result1 = upsertContract({ ...contractA, status: 'Completed', version: v1 });
expect(result1).toEqual({ success: true, stale: false });
const v2 = getContractVersion(contractA.contractName);
expect(v2).toBe(1);
const result2 = upsertContract({ ...contractA, status: 'Disputed', version: v2 });
expect(result2).toEqual({ success: true, stale: false });
expect(getContractVersion(contractA.contractName)).toBe(2);
});
});
});
describe('getContractVersion', () => {
it('returns 0 when the contract has never been persisted', () => {
expect(getContractVersion('NonExistent')).toBe(0);
});
it('returns 0 for a freshly saved contract (no version set)', () => {
saveContract(contractA);
expect(getContractVersion(contractA.contractName)).toBe(0);
});
it('returns the version set by the last upsert', () => {
saveContract(contractA);
upsertContract({ ...contractA, status: 'Completed', version: 0 });
expect(getContractVersion(contractA.contractName)).toBe(1);
});
});
describe('updateContract', () => {
it('replaces the contract found by its original name, in place', () => {
saveContract(contractA);
saveContract(contractB);
const edited: Contract = { ...contractA, status: 'Completed' };
expect(updateContract(contractA.contractName, edited)).toBe(true);
const result = listContracts();
expect(result).toHaveLength(2);
expect(result[0]).toEqual(edited);
expect(result[1]).toEqual(contractB);
});
it('renames a contract without creating a duplicate', () => {
saveContract(contractA);
const renamed: Contract = { ...contractA, contractName: 'Renamed Alpha' };
expect(updateContract(contractA.contractName, renamed)).toBe(true);
const result = listContracts();
expect(result).toHaveLength(1);
expect(result[0].contractName).toBe('Renamed Alpha');
});
it('returns false and changes nothing when no contract matches the original name', () => {
saveContract(contractA);
expect(updateContract('Missing Contract', contractB)).toBe(false);
expect(listContracts()).toEqual([contractA]);
});
it('leaves milestones untouched', () => {
saveContract(contractA);
saveMilestone(milestoneA);
updateContract(contractA.contractName, { ...contractA, status: 'Paid' });
expect(listMilestones()).toEqual([milestoneA]);
});
});
describe('milestone round-trip', () => {
it('saves a milestone and reads it back', () => {
saveMilestone(milestoneA);
expect(listMilestones()).toEqual([milestoneA]);
});
it('preserves all Milestone fields intact', () => {
saveMilestone(milestoneA);
const [result] = listMilestones();
expect(result.id).toBe('ms-001');
expect(result.title).toBe('Kickoff');
expect(result.status).toBe('Pending');
expect(result.payout).toBe(500);
expect(result.dueDate).toBe('Mar 1, 2025');
});
});
describe('updateMilestone operation', () => {
it('updates an existing milestone by id', () => {
saveMilestone(milestoneA);
const updated = { status: 'Completed' } as Partial<Milestone>;
expect(updateMilestone('ms-001', updated)).toBe(true);
const [result] = listMilestones();
expect(result.status).toBe('Completed');
});
it('returns false and warns when id not found', () => {
jest.spyOn(console, 'warn').mockImplementation(() => {});
expect(updateMilestone('non-existent', { status: 'Paid' })).toBe(false);
expect(console.warn).toHaveBeenCalled();
});
it('does not mutate original milestone object', () => {
saveMilestone(milestoneA);
const original = { ...milestoneA };
updateMilestone('ms-001', { status: 'Disputed' });
expect(milestoneA).toEqual(original);
});
});
// ===========================================================================
// 3. MULTIPLE WRITES ARE ADDITIVE
// ===========================================================================
describe('multiple saves are additive', () => {
it('accumulates multiple contracts', () => {
saveContract(contractA);
saveContract(contractB);
const result = listContracts();
expect(result).toHaveLength(2);
expect(result[0]).toEqual(contractA);
expect(result[1]).toEqual(contractB);
});
it('accumulates multiple milestones', () => {
saveMilestone(milestoneA);
saveMilestone(milestoneB);
const result = listMilestones();
expect(result).toHaveLength(2);
expect(result[0]).toEqual(milestoneA);
expect(result[1]).toEqual(milestoneB);
});
});
// ===========================================================================
// 4. DATA ISOLATION — contracts and milestones never overwrite each other
// ===========================================================================
describe('data isolation', () => {
it('saving a contract does not erase existing milestones', () => {
saveMilestone(milestoneA);
saveMilestone(milestoneB);
saveContract(contractA);
// Milestones must still be intact
expect(listMilestones()).toHaveLength(2);
expect(listMilestones()[0]).toEqual(milestoneA);
// Contract also persisted
expect(listContracts()).toHaveLength(1);
});
it('saving a milestone does not erase existing contracts', () => {
saveContract(contractA);
saveContract(contractB);
saveMilestone(milestoneA);
// Contracts must still be intact
expect(listContracts()).toHaveLength(2);
expect(listContracts()[1]).toEqual(contractB);
// Milestone also persisted
expect(listMilestones()).toHaveLength(1);
});
it('interleaved saves preserve the full data set', () => {
saveContract(contractA);
saveMilestone(milestoneA);
saveContract(contractB);
saveMilestone(milestoneB);
expect(listContracts()).toEqual([contractA, contractB]);
expect(listMilestones()).toEqual([milestoneA, milestoneB]);
});
});
// ===========================================================================
// 5. CORRUPT / INVALID DATA HANDLING
// ===========================================================================
describe('corrupt data handling', () => {
let mockReporter: jest.Mock;
beforeEach(() => {
mockReporter = jest.fn();
setErrorReporter(mockReporter);
});
afterEach(() => {
setErrorReporter(null);
});
it('returns [] for contracts when localStorage contains invalid JSON', () => {
seedRaw('%%%not-json%%%');
expect(listContracts()).toEqual([]);
});
it('returns [] for milestones when localStorage contains invalid JSON', () => {
seedRaw('%%%not-json%%%');
expect(listMilestones()).toEqual([]);
});
it('calls the error reporter on parse failure', () => {
seedRaw('{invalid}');
listContracts();
expect(mockReporter).toHaveBeenCalledTimes(1);
expect(mockReporter.mock.calls[0][1]).toMatch(/\[repository\]/);
});
it('returns [] when stored value is a JSON string (not an object)', () => {
seedRaw('"just-a-string"');
expect(listContracts()).toEqual([]);
expect(listMilestones()).toEqual([]);
});
it('returns [] when stored value is a JSON number', () => {
seedRaw('42');
expect(listContracts()).toEqual([]);
expect(listMilestones()).toEqual([]);
});
it('returns [] when stored value is a JSON array at the top level', () => {
seedRaw('[]');
expect(listContracts()).toEqual([]);
expect(listMilestones()).toEqual([]);
});
it('recovers contracts array when only milestones key is missing from stored object', () => {
window.localStorage.setItem(
STORAGE_KEY,
JSON.stringify({ contracts: [contractA] }),
);
expect(listContracts()).toEqual([contractA]);
// Missing milestones key falls back to []
expect(listMilestones()).toEqual([]);
});
it('recovers milestones array when only contracts key is missing from stored object', () => {
window.localStorage.setItem(
STORAGE_KEY,
JSON.stringify({ milestones: [milestoneA] }),
);
expect(listMilestones()).toEqual([milestoneA]);
// Missing contracts key falls back to []
expect(listContracts()).toEqual([]);
});
it('does not throw even when localStorage.getItem throws', () => {
jest.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
throw new Error('storage quota exceeded');
});
expect(() => listContracts()).not.toThrow();
expect(listContracts()).toEqual([]);
});
it('reports the error via the central reporter when getItem throws', () => {
jest.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
throw new Error('storage quota exceeded');
});
listContracts();
expect(mockReporter).toHaveBeenCalledTimes(1);
expect(mockReporter.mock.calls[0][0]).toBeInstanceOf(Error);
expect(mockReporter.mock.calls[0][1]).toMatch(/\[repository\]/);
});
});
// ===========================================================================
// 6. SSR CONTEXT ISOLATION (window is undefined)
// ===========================================================================
describe('SSR context isolation', () => {
// Note: The original SSR tests used `delete global.window` to simulate SSR,
// but in Jest 30 / jsdom `global.window` is a non-configurable property.
// Instead of modifying globals, we mock localStorage to throw, which exercises
// the error-recovery path (catch blocks) and verifies functions never throw.
// The SSR guard (isBrowser) is tested directly in the 'isBrowser' unit test below.
function mockStorageUnavailable() {
jest.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
throw new Error('localStorage unavailable (SSR)');
});
jest.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new Error('localStorage unavailable (SSR)');
});
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new Error('localStorage unavailable (SSR)');
});
}
it('listContracts returns [] without throwing when storage is unavailable', () => {
mockStorageUnavailable();
expect(() => listContracts()).not.toThrow();
expect(listContracts()).toEqual([]);
});
it('listMilestones returns [] without throwing when storage is unavailable', () => {
mockStorageUnavailable();
expect(() => listMilestones()).not.toThrow();
expect(listMilestones()).toEqual([]);
});
it('saveContract does not throw when storage is unavailable', () => {
mockStorageUnavailable();
expect(() => saveContract(contractA)).not.toThrow();
});
it('saveMilestone does not throw when storage is unavailable', () => {
mockStorageUnavailable();
expect(() => saveMilestone(milestoneA)).not.toThrow();
});
it('data saved before SSR simulation is not affected after window is restored', () => {
saveContract(contractA);
mockStorageUnavailable();
// Call must not throw
listContracts();
jest.restoreAllMocks();
// Original data is still intact
expect(listContracts()).toEqual([contractA]);
});
});
// ===========================================================================
// 7. WRITE FAILURE RESILIENCE
// ===========================================================================
describe('write failure resilience', () => {
let mockReporter: jest.Mock;
beforeEach(() => {
mockReporter = jest.fn();
setErrorReporter(mockReporter);
});
afterEach(() => {
setErrorReporter(null);
});
it('does not throw when localStorage.setItem throws', () => {
jest.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError');
});
expect(() => saveContract(contractA)).not.toThrow();
});
it('calls the error reporter when setItem throws', () => {
jest.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError');
});
saveContract(contractA);
expect(mockReporter).toHaveBeenCalledTimes(1);
expect(mockReporter.mock.calls[0][1]).toMatch(/\[repository\]/);
});
it('returns { success: false, stale: false } and reports the error when upsertContract fails to persist the write', () => {
jest.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
throw new DOMException('QuotaExceededError');
});
const result = upsertContract({ ...contractA, version: 0 });
expect(result).toEqual({ success: false, stale: false });
expect(mockReporter).toHaveBeenCalledTimes(1);
expect(mockReporter.mock.calls[0][1]).toMatch(/\[repository\]/);
});
});
// ===========================================================================
// 8. CLEAR APP DATA
// ===========================================================================
describe('clearAppData', () => {
let mockReporter: jest.Mock;
beforeEach(() => {
mockReporter = jest.fn();
setErrorReporter(mockReporter);
});
afterEach(() => {
setErrorReporter(null);
});
it('returns true and removes STORAGE_KEY on success', () => {
saveContract(contractA);
expect(window.localStorage.getItem(STORAGE_KEY)).not.toBeNull();
expect(clearAppData()).toBe(true);
expect(window.localStorage.getItem(STORAGE_KEY)).toBeNull();
});
it('listContracts returns [] after clearAppData', () => {
saveContract(contractA);
saveContract(contractB);
clearAppData();
expect(listContracts()).toEqual([]);
});
it('listMilestones returns [] after clearAppData', () => {
saveMilestone(milestoneA);
clearAppData();
expect(listMilestones()).toEqual([]);
});
it('clears both contracts and milestones in a single call', () => {
saveContract(contractA);
saveMilestone(milestoneA);
clearAppData();
expect(listContracts()).toEqual([]);
expect(listMilestones()).toEqual([]);
});
it('returns true even when the key was never set (idempotent)', () => {
// localStorage is already empty from beforeEach
expect(clearAppData()).toBe(true);
});
it('does not call the error reporter on a normal removal', () => {
saveContract(contractA);
clearAppData();
expect(mockReporter).not.toHaveBeenCalled();
});
it('returns false and reports the error when removeItem throws', () => {
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new DOMException('SecurityError');
});
expect(clearAppData()).toBe(false);
expect(mockReporter).toHaveBeenCalledTimes(1);
expect(mockReporter.mock.calls[0][1]).toMatch(/\[repository\]/);
expect(mockReporter.mock.calls[0][0]).toBeInstanceOf(DOMException);
});
it('does not throw even when removeItem throws', () => {
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new DOMException('SecurityError');
});
expect(() => clearAppData()).not.toThrow();
});
describe('SSR context', () => {
it('returns false and does not throw when storage.removeItem throws', () => {
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new DOMException('Not available');
});
expect(() => clearAppData()).not.toThrow();
expect(clearAppData()).toBe(false);
});
});
});
// ===========================================================================
// 9. CLEAR BY PREFIX
// ===========================================================================
describe('clearByPrefix', () => {
let mockReporter: jest.Mock;
beforeEach(() => {
mockReporter = jest.fn();
setErrorReporter(mockReporter);
});
afterEach(() => {
setErrorReporter(null);
});
// -------------------------------------------------------------------------
// Basic success path
// -------------------------------------------------------------------------
it('removes all keys matching the prefix and returns the count', () => {
window.localStorage.setItem('talenttrust_alpha', 'a');
window.localStorage.setItem('talenttrust_beta', 'b');
window.localStorage.setItem('talenttrust_gamma', 'c');
const removed = clearByPrefix('talenttrust_');
expect(removed).toBe(3);
expect(window.localStorage.getItem('talenttrust_alpha')).toBeNull();
expect(window.localStorage.getItem('talenttrust_beta')).toBeNull();
expect(window.localStorage.getItem('talenttrust_gamma')).toBeNull();
});
it('removes the STORAGE_KEY when using the talenttrust_ prefix', () => {
saveContract(contractA);
// STORAGE_KEY = 'talenttrust_app_data' which starts with 'talenttrust_'
const removed = clearByPrefix('talenttrust_');
expect(removed).toBeGreaterThanOrEqual(1);
expect(window.localStorage.getItem(STORAGE_KEY)).toBeNull();
});
// -------------------------------------------------------------------------
// Prefix scoping — unrelated keys must never be touched
// -------------------------------------------------------------------------
it('does NOT remove keys that do not match the prefix', () => {
window.localStorage.setItem('talenttrust_mykey', 'tt');
window.localStorage.setItem('other_service_key', 'unrelated');
window.localStorage.setItem('another_key', 'also-unrelated');
const removed = clearByPrefix('talenttrust_');
expect(removed).toBe(1);
expect(window.localStorage.getItem('other_service_key')).toBe('unrelated');
expect(window.localStorage.getItem('another_key')).toBe('also-unrelated');
});
it('only removes keys with the exact prefix, not keys that merely contain it', () => {
window.localStorage.setItem('talenttrust_real', 'yes');
window.localStorage.setItem('prefix_talenttrust_embedded', 'no');
const removed = clearByPrefix('talenttrust_');
expect(removed).toBe(1);
expect(window.localStorage.getItem('prefix_talenttrust_embedded')).toBe('no');
});
it('does not remove keys that have the prefix as a suffix', () => {
window.localStorage.setItem('talenttrust_a', '1');
window.localStorage.setItem('not_talenttrust_', '2');
clearByPrefix('talenttrust_');
expect(window.localStorage.getItem('not_talenttrust_')).toBe('2');
});
// -------------------------------------------------------------------------
// Edge cases
// -------------------------------------------------------------------------
it('returns 0 when no keys match the prefix', () => {
window.localStorage.setItem('other_key', 'value');
expect(clearByPrefix('talenttrust_')).toBe(0);
});
it('returns 0 when localStorage is empty', () => {
// localStorage cleared in beforeEach
expect(clearByPrefix('talenttrust_')).toBe(0);
});
it('handles mixed matching and non-matching keys correctly', () => {
window.localStorage.setItem('talenttrust_x', '1');
window.localStorage.setItem('unrelated_y', '2');
window.localStorage.setItem('talenttrust_z', '3');
window.localStorage.setItem('something_else', '4');
const removed = clearByPrefix('talenttrust_');
expect(removed).toBe(2);
expect(window.localStorage.getItem('talenttrust_x')).toBeNull();
expect(window.localStorage.getItem('talenttrust_z')).toBeNull();
expect(window.localStorage.getItem('unrelated_y')).toBe('2');
expect(window.localStorage.getItem('something_else')).toBe('4');
});
it('does not call the error reporter when removal succeeds', () => {
window.localStorage.setItem('talenttrust_ok', 'data');
clearByPrefix('talenttrust_');
expect(mockReporter).not.toHaveBeenCalled();
});
// -------------------------------------------------------------------------
// Error handling — throwing removeItem
// -------------------------------------------------------------------------
it('does not throw when removeItem throws for a matched key', () => {
window.localStorage.setItem('talenttrust_fail', 'data');
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new DOMException('SecurityError');
});
expect(() => clearByPrefix('talenttrust_')).not.toThrow();
});
it('reports an error via the central reporter when removeItem throws', () => {
window.localStorage.setItem('talenttrust_fail', 'data');
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new DOMException('SecurityError');
});
clearByPrefix('talenttrust_');
expect(mockReporter).toHaveBeenCalledTimes(1);
expect(mockReporter.mock.calls[0][1]).toMatch(/\[repository\]/);
expect(mockReporter.mock.calls[0][0]).toBeInstanceOf(DOMException);
});
it('does not increment the removal count for a key that throws', () => {
window.localStorage.setItem('talenttrust_fail', 'data');
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
throw new DOMException('SecurityError');
});
const removed = clearByPrefix('talenttrust_');
expect(removed).toBe(0);
});
it('continues removing other keys after one removal fails', () => {
// Seed two matching keys. The mock will succeed for 'talenttrust_b' but
// we verify total reporter calls to confirm partial success handling.
window.localStorage.setItem('talenttrust_a', '1');
window.localStorage.setItem('talenttrust_b', '2');
let callCount = 0;
jest.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {
callCount += 1;
if (callCount === 1) throw new DOMException('SecurityError');
// Allow the second removal to proceed via real localStorage
});
// One removal throws → count = 0 for that key; the second succeeds.
// We verify that the function attempted both keys and reported once.
const removed = clearByPrefix('talenttrust_');
expect(mockReporter).toHaveBeenCalledTimes(1);
expect(removed).toBe(1);
});
// -------------------------------------------------------------------------
// SSR context
// -------------------------------------------------------------------------
describe('SSR context', () => {
it('returns 0 without throwing when storage is unavailable', () => {
// Mock localStorage.key to be empty (simulating SSR)
jest.spyOn(window.localStorage, 'length', 'get').mockReturnValue(0);
expect(() => clearByPrefix('talenttrust_')).not.toThrow();
expect(clearByPrefix('talenttrust_')).toBe(0);
});
it('does not call the error reporter when storage is unavailable', () => {
jest.spyOn(window.localStorage, 'length', 'get').mockReturnValue(0);
clearByPrefix('talenttrust_');
expect(mockReporter).not.toHaveBeenCalled();
});
});
});
// ===========================================================================
// deleteMilestones
// ===========================================================================
describe('deleteMilestones', () => {
const milestoneC: Milestone = {
id: 'ms-003',
title: 'Review',
status: 'Active',
payout: 750,
currency: 'USD',
dueDate: 'May 1, 2025',
};
const seedThreeMilestones = () => {
saveMilestone(milestoneA);
saveMilestone(milestoneB);
saveMilestone(milestoneC);
};
it('returns 0 when given an empty array', () => {
saveMilestone(milestoneA);
expect(deleteMilestones([])).toBe(0);
expect(listMilestones()).toHaveLength(1);
});
it('returns 0 when input is not an array', () => {
saveMilestone(milestoneA);
expect(deleteMilestones(null as unknown as string[])).toBe(0);
expect(listMilestones()).toHaveLength(1);
});
it('deletes a single milestone by id and returns count of 1', () => {
seedThreeMilestones();
const removed = deleteMilestones(['ms-002']);
expect(removed).toBe(1);
const remaining = listMilestones();
expect(remaining).toHaveLength(2);
expect(remaining.map((m) => m.id)).toEqual(expect.arrayContaining(['ms-001', 'ms-003']));
expect(remaining.map((m) => m.id)).not.toContain('ms-002');
});
it('deletes multiple milestones and returns the actual deletion count', () => {
seedThreeMilestones();
const removed = deleteMilestones(['ms-001', 'ms-003']);
expect(removed).toBe(2);
const remaining = listMilestones();
expect(remaining).toHaveLength(1);
expect(remaining[0].id).toBe('ms-002');
});
it('silently skips ids that do not exist (partial match)', () => {
seedThreeMilestones();
const removed = deleteMilestones(['ms-001', 'ms-NOEXIST', 'ms-999']);
expect(removed).toBe(1);