-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathimplementation.spec.js
More file actions
848 lines (681 loc) · 27.4 KB
/
implementation.spec.js
File metadata and controls
848 lines (681 loc) · 27.4 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
import { Cursor, CURSOR_COMPATIBILITY_SYMBOL } from 'decap-cms-lib-util';
import GitHubImplementation from '../implementation';
jest.spyOn(console, 'error').mockImplementation(() => {});
describe('github backend implementation', () => {
const config = {
backend: {
repo: 'owner/repo',
open_authoring: false,
api_root: 'https://api.github.com',
},
};
const configWithNotes = {
backend: {
repo: 'owner/repo',
open_authoring: false,
api_root: 'https://api.github.com',
},
editor: {
notes: true,
},
};
const createObjectURL = jest.fn();
global.URL = {
createObjectURL,
};
createObjectURL.mockReturnValue('displayURL');
beforeEach(() => {
jest.clearAllMocks();
});
describe('forkExists', () => {
it('should return true when repo is fork and parent matches originRepo', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.currentUser = jest.fn().mockResolvedValue({ login: 'login' });
global.fetch = jest.fn().mockResolvedValue({
// matching should be case-insensitive
json: () => ({ fork: true, parent: { full_name: 'OWNER/REPO' } }),
});
await expect(gitHubImplementation.forkExists({ token: 'token' })).resolves.toBe(true);
expect(gitHubImplementation.currentUser).toHaveBeenCalledTimes(1);
expect(gitHubImplementation.currentUser).toHaveBeenCalledWith({ token: 'token' });
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith('https://api.github.com/repos/login/repo', {
method: 'GET',
headers: {
Authorization: 'token token',
},
signal: expect.any(AbortSignal),
});
});
it('should return false when repo is not a fork', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.currentUser = jest.fn().mockResolvedValue({ login: 'login' });
global.fetch = jest.fn().mockResolvedValue({
// matching should be case-insensitive
json: () => ({ fork: false }),
});
expect.assertions(1);
await expect(gitHubImplementation.forkExists({ token: 'token' })).resolves.toBe(false);
});
it("should return false when parent doesn't match originRepo", async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.currentUser = jest.fn().mockResolvedValue({ login: 'login' });
global.fetch = jest.fn().mockResolvedValue({
json: () => ({ fork: true, parent: { full_name: 'owner/other_repo' } }),
});
expect.assertions(1);
await expect(gitHubImplementation.forkExists({ token: 'token' })).resolves.toBe(false);
});
});
describe('persistMedia', () => {
const persistFiles = jest.fn();
const mockAPI = {
persistFiles,
};
persistFiles.mockImplementation((_, files) => {
files.forEach((file, index) => {
file.sha = index;
});
});
it('should persist media file', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const mediaFile = {
fileObj: { size: 100, name: 'image.png' },
path: '/media/image.png',
};
expect.assertions(5);
await expect(gitHubImplementation.persistMedia(mediaFile, {})).resolves.toEqual({
id: 0,
name: 'image.png',
size: 100,
displayURL: 'displayURL',
path: 'media/image.png',
});
expect(persistFiles).toHaveBeenCalledTimes(1);
expect(persistFiles).toHaveBeenCalledWith([], [mediaFile], {});
expect(createObjectURL).toHaveBeenCalledTimes(1);
expect(createObjectURL).toHaveBeenCalledWith(mediaFile.fileObj);
});
it('should log and throw error on "persistFiles" error', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const error = new Error('failed to persist files');
persistFiles.mockRejectedValue(error);
const mediaFile = {
value: 'image.png',
fileObj: { size: 100 },
path: '/media/image.png',
};
expect.assertions(5);
await expect(gitHubImplementation.persistMedia(mediaFile)).rejects.toThrowError(error);
expect(persistFiles).toHaveBeenCalledTimes(1);
expect(createObjectURL).toHaveBeenCalledTimes(0);
expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledWith(error);
});
});
describe('unpublishedEntry', () => {
const generateContentKey = jest.fn();
const retrieveUnpublishedEntryData = jest.fn();
const mockAPI = {
generateContentKey,
retrieveUnpublishedEntryData,
};
it('should return unpublished entry data', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
gitHubImplementation.loadEntryMediaFiles = jest
.fn()
.mockResolvedValue([{ path: 'image.png', id: 'sha' }]);
generateContentKey.mockReturnValue('contentKey');
const data = {
collection: 'collection',
slug: 'slug',
status: 'draft',
diffs: [],
updatedAt: 'updatedAt',
};
retrieveUnpublishedEntryData.mockResolvedValue(data);
const collection = 'posts';
const slug = 'slug';
await expect(gitHubImplementation.unpublishedEntry({ collection, slug })).resolves.toEqual(
data,
);
expect(generateContentKey).toHaveBeenCalledTimes(1);
expect(generateContentKey).toHaveBeenCalledWith('posts', 'slug');
expect(retrieveUnpublishedEntryData).toHaveBeenCalledTimes(1);
expect(retrieveUnpublishedEntryData).toHaveBeenCalledWith('contentKey');
});
});
describe('entriesByFolder', () => {
const listFiles = jest.fn();
const readFile = jest.fn();
const readFileMetadata = jest.fn(() => Promise.resolve({ author: '', updatedOn: '' }));
const mockAPI = {
listFiles,
readFile,
readFileMetadata,
originRepoURL: 'originRepoURL',
};
it('should return entries and cursor', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const files = [];
const count = 1501;
for (let i = 0; i < count; i++) {
const id = `${i}`.padStart(`${count}`.length, '0');
files.push({
id,
path: `posts/post-${id}.md`,
});
}
listFiles.mockResolvedValue(files);
readFile.mockImplementation((path, id) => Promise.resolve(`${id}`));
const expectedEntries = files
.slice(0, 20)
.map(({ id, path }) => ({ data: id, file: { path, id, author: '', updatedOn: '' } }));
const expectedCursor = Cursor.create({
actions: ['next', 'last'],
meta: { page: 1, count, pageSize: 20, pageCount: 76 },
data: { files },
});
expectedEntries[CURSOR_COMPATIBILITY_SYMBOL] = expectedCursor;
const result = await gitHubImplementation.entriesByFolder('posts', 'md', 1);
expect(result).toEqual(expectedEntries);
expect(listFiles).toHaveBeenCalledTimes(1);
expect(listFiles).toHaveBeenCalledWith('posts', { depth: 1, repoURL: 'originRepoURL' });
expect(readFile).toHaveBeenCalledTimes(20);
});
});
describe('traverseCursor', () => {
const listFiles = jest.fn();
const readFile = jest.fn((path, id) => Promise.resolve(`${id}`));
const readFileMetadata = jest.fn(() => Promise.resolve({}));
const mockAPI = {
listFiles,
readFile,
originRepoURL: 'originRepoURL',
readFileMetadata,
};
const files = [];
const count = 1501;
for (let i = 0; i < count; i++) {
const id = `${i}`.padStart(`${count}`.length, '0');
files.push({
id,
path: `posts/post-${id}.md`,
});
}
it('should handle next action', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const cursor = Cursor.create({
actions: ['next', 'last'],
meta: { page: 1, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const expectedEntries = files
.slice(20, 40)
.map(({ id, path }) => ({ data: id, file: { path, id } }));
const expectedCursor = Cursor.create({
actions: ['prev', 'first', 'next', 'last'],
meta: { page: 2, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const result = await gitHubImplementation.traverseCursor(cursor, 'next');
expect(result).toEqual({
entries: expectedEntries,
cursor: expectedCursor,
});
});
it('should handle prev action', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const cursor = Cursor.create({
actions: ['prev', 'first', 'next', 'last'],
meta: { page: 2, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const expectedEntries = files
.slice(0, 20)
.map(({ id, path }) => ({ data: id, file: { path, id } }));
const expectedCursor = Cursor.create({
actions: ['next', 'last'],
meta: { page: 1, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const result = await gitHubImplementation.traverseCursor(cursor, 'prev');
expect(result).toEqual({
entries: expectedEntries,
cursor: expectedCursor,
});
});
it('should handle last action', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const cursor = Cursor.create({
actions: ['next', 'last'],
meta: { page: 1, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const expectedEntries = files
.slice(1500)
.map(({ id, path }) => ({ data: id, file: { path, id } }));
const expectedCursor = Cursor.create({
actions: ['prev', 'first'],
meta: { page: 76, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const result = await gitHubImplementation.traverseCursor(cursor, 'last');
expect(result).toEqual({
entries: expectedEntries,
cursor: expectedCursor,
});
});
it('should handle first action', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const cursor = Cursor.create({
actions: ['prev', 'first'],
meta: { page: 76, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const expectedEntries = files
.slice(0, 20)
.map(({ id, path }) => ({ data: id, file: { path, id } }));
const expectedCursor = Cursor.create({
actions: ['next', 'last'],
meta: { page: 1, count, pageSize: 20, pageCount: 76 },
data: { files },
});
const result = await gitHubImplementation.traverseCursor(cursor, 'first');
expect(result).toEqual({
entries: expectedEntries,
cursor: expectedCursor,
});
});
});
describe('notes implementation', () => {
const mockAPI = {
getEntryNotes: jest.fn(),
addNoteToEntry: jest.fn(),
updateEntryNote: jest.fn(),
deleteEntryNote: jest.fn(),
closeEntryNotesIssue: jest.fn(),
closeIssueOnPublish: jest.fn(),
reopenIssueOnUnpublish: jest.fn(),
readFile: jest.fn(),
deleteUnpublishedEntry: jest.fn().mockResolvedValue(undefined),
publishUnpublishedEntry: jest.fn().mockResolvedValue(undefined),
};
beforeEach(() => {
jest.clearAllMocks();
});
describe('getNotes', () => {
it('should retrieve notes for an entry', async () => {
const gitHubImplementation = new GitHubImplementation(configWithNotes);
gitHubImplementation.api = mockAPI;
const mockNotes = [
{
id: '1',
author: 'user1',
avatarUrl: 'https://avatar.url',
text: 'Test note',
timestamp: '2025-01-01T00:00:00Z',
resolved: false,
},
];
mockAPI.getEntryNotes.mockResolvedValue(mockNotes);
const result = await gitHubImplementation.getNotes('posts', 'my-post');
expect(result).toEqual([
{
...mockNotes[0],
entrySlug: 'my-post',
},
]);
expect(mockAPI.getEntryNotes).toHaveBeenCalledWith('posts', 'my-post');
});
it('should return empty array on error', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
mockAPI.getEntryNotes.mockRejectedValue(new Error('API Error'));
const result = await gitHubImplementation.getNotes('posts', 'my-post');
expect(result).toEqual([]);
expect(console.error).toHaveBeenCalledWith('Failed to get notes:', expect.any(Error));
});
});
describe('addNote', () => {
it('should add a note to an entry', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
gitHubImplementation.token = 'test-token';
gitHubImplementation.currentUser = jest.fn().mockResolvedValue({
login: 'testuser',
name: 'Test User',
avatar_url: 'https://avatar.url',
});
const noteData = {
text: 'New note',
timestamp: '2025-01-01T00:00:00Z',
resolved: false,
};
mockAPI.addNoteToEntry.mockResolvedValue({
commentId: 'comment-123',
issueUrl: 'https://github.com/owner/repo/issues/1',
});
mockAPI.readFile.mockResolvedValue('title: My Post Title\n\nContent');
const result = await gitHubImplementation.addNote('posts', 'my-post', noteData);
expect(result).toMatchObject({
text: 'New note',
author: 'testuser',
avatarUrl: 'https://avatar.url',
entrySlug: 'my-post',
resolved: false,
id: 'comment-123',
});
expect(mockAPI.addNoteToEntry).toHaveBeenCalledWith(
'posts',
'my-post',
expect.objectContaining({
text: 'New note',
author: 'testuser',
}),
'My Post Title',
);
});
it('should handle missing entry title gracefully', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
gitHubImplementation.token = 'test-token';
gitHubImplementation.currentUser = jest.fn().mockResolvedValue({
login: 'testuser',
avatar_url: 'https://avatar.url',
});
const noteData = {
text: 'New note',
timestamp: '2025-01-01T00:00:00Z',
};
mockAPI.addNoteToEntry.mockResolvedValue({
commentId: 'comment-123',
issueUrl: 'https://github.com/owner/repo/issues/1',
});
mockAPI.readFile.mockRejectedValue(new Error('Not found'));
const result = await gitHubImplementation.addNote('posts', 'my-post', noteData);
expect(mockAPI.addNoteToEntry).toHaveBeenCalledWith(
'posts',
'my-post',
expect.any(Object),
undefined,
);
expect(result.id).toBe('comment-123');
});
});
describe('updateNote', () => {
it('should update an existing note', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const existingNotes = [
{
id: 'note-1',
author: 'user1',
avatarUrl: 'https://avatar.url',
text: 'Original text',
timestamp: '2025-01-01T00:00:00Z',
resolved: false,
entrySlug: 'my-post',
},
];
mockAPI.getEntryNotes.mockResolvedValue(existingNotes);
mockAPI.updateEntryNote.mockResolvedValue(undefined);
const updates = { text: 'Updated text', resolved: true };
const result = await gitHubImplementation.updateNote('posts', 'my-post', 'note-1', updates);
expect(result).toEqual({
...existingNotes[0],
text: 'Updated text',
resolved: true,
});
expect(mockAPI.updateEntryNote).toHaveBeenCalledWith('note-1', result);
});
it('should throw error if note not found', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
mockAPI.getEntryNotes.mockResolvedValue([]);
await expect(
gitHubImplementation.updateNote('posts', 'my-post', 'non-existent', {}),
).rejects.toThrow('Note with ID non-existent not found');
});
});
describe('deleteNote', () => {
it('should delete an existing note', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const existingNotes = [
{
id: 'note-1',
author: 'user1',
text: 'Test note',
entrySlug: 'my-post',
},
];
mockAPI.getEntryNotes.mockResolvedValue(existingNotes);
mockAPI.deleteEntryNote.mockResolvedValue(undefined);
await gitHubImplementation.deleteNote('posts', 'my-post', 'note-1');
expect(mockAPI.deleteEntryNote).toHaveBeenCalledWith('note-1');
});
it('should throw error if note not found', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
mockAPI.getEntryNotes.mockResolvedValue([]);
await expect(
gitHubImplementation.deleteNote('posts', 'my-post', 'non-existent'),
).rejects.toThrow('Note with ID non-existent not found');
});
});
describe('toggleNoteResolution', () => {
it('should toggle note resolved status from false to true', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const existingNotes = [
{
id: 'note-1',
author: 'user1',
avatarUrl: 'https://avatar.url',
text: 'Test note',
timestamp: '2025-01-01T00:00:00Z',
resolved: false,
entrySlug: 'my-post',
},
];
mockAPI.getEntryNotes.mockResolvedValue(existingNotes);
mockAPI.updateEntryNote.mockResolvedValue(undefined);
const result = await gitHubImplementation.toggleNoteResolution(
'posts',
'my-post',
'note-1',
);
expect(result.resolved).toBe(true);
expect(mockAPI.updateEntryNote).toHaveBeenCalledWith(
'note-1',
expect.objectContaining({ resolved: true }),
);
});
it('should toggle note resolved status from true to false', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
const existingNotes = [
{
id: 'note-1',
resolved: true,
entrySlug: 'my-post',
},
];
mockAPI.getEntryNotes.mockResolvedValue(existingNotes);
mockAPI.updateEntryNote.mockResolvedValue(undefined);
const result = await gitHubImplementation.toggleNoteResolution(
'posts',
'my-post',
'note-1',
);
expect(result.resolved).toBe(false);
});
it('should throw error if note not found', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
mockAPI.getEntryNotes.mockResolvedValue([]);
await expect(
gitHubImplementation.toggleNoteResolution('posts', 'my-post', 'non-existent'),
).rejects.toThrow('Note with ID non-existent not found');
});
});
describe('reopenIssueForUnpublishedEntry', () => {
it('should reopen issue for unpublished entry', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
mockAPI.reopenIssueOnUnpublish.mockResolvedValue(undefined);
await gitHubImplementation.reopenIssueForUnpublishedEntry('posts', 'my-post');
expect(mockAPI.reopenIssueOnUnpublish).toHaveBeenCalledWith('posts', 'my-post');
});
});
describe('deleteUnpublishedEntry with notes cleanup', () => {
it('should delete entry and close associated notes issue', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI; // Just use mockAPI directly
await gitHubImplementation.deleteUnpublishedEntry('posts', 'my-post');
expect(mockAPI.deleteUnpublishedEntry).toHaveBeenCalledWith('posts', 'my-post');
expect(mockAPI.closeEntryNotesIssue).toHaveBeenCalledWith('posts', 'my-post');
});
it('should continue deletion even if closing issue fails', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
mockAPI.closeEntryNotesIssue.mockRejectedValue(new Error('Issue close failed'));
await gitHubImplementation.deleteUnpublishedEntry('posts', 'my-post');
expect(mockAPI.deleteUnpublishedEntry).toHaveBeenCalledWith('posts', 'my-post');
});
});
describe('publishUnpublishedEntry with issue cleanup', () => {
it('should publish entry and close issue', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.api = mockAPI;
await gitHubImplementation.publishUnpublishedEntry('posts', 'my-post');
expect(mockAPI.publishUnpublishedEntry).toHaveBeenCalledWith('posts', 'my-post');
expect(mockAPI.closeIssueOnPublish).toHaveBeenCalledWith('posts', 'my-post');
});
});
describe('notes polling', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should start notes polling', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.pollingManager = {
watchIssueWithRetry: jest.fn().mockResolvedValue(() => {}),
getStatus: jest.fn().mockReturnValue({ currentWatch: null }),
};
const callbacks = {
onUpdate: jest.fn(),
onChange: jest.fn(),
};
await gitHubImplementation.startNotesPolling('posts', 'my-post', callbacks);
expect(gitHubImplementation.pollingManager.watchIssueWithRetry).toHaveBeenCalledWith(
'posts',
'my-post',
callbacks,
5,
2000,
);
});
it('should not start polling if already watching same entry', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.pollingManager = {
watchIssueWithRetry: jest.fn().mockResolvedValue(() => {}),
getStatus: jest.fn().mockReturnValue({ currentWatch: 'posts/my-post' }),
};
const callbacks = { onUpdate: jest.fn() };
await gitHubImplementation.startNotesPolling('posts', 'my-post', callbacks);
expect(gitHubImplementation.pollingManager.watchIssueWithRetry).not.toHaveBeenCalled();
});
it('should stop notes polling', async () => {
const gitHubImplementation = new GitHubImplementation(config);
const unwatchFn = jest.fn();
gitHubImplementation.unwatchFunctions.set('posts/my-post', unwatchFn);
await gitHubImplementation.stopNotesPolling('posts', 'my-post');
expect(unwatchFn).toHaveBeenCalledTimes(1);
expect(gitHubImplementation.unwatchFunctions.has('posts/my-post')).toBe(false);
});
it('should handle stopping polling when not active', async () => {
const gitHubImplementation = new GitHubImplementation(config);
await expect(
gitHubImplementation.stopNotesPolling('posts', 'my-post'),
).resolves.not.toThrow();
});
it('should refresh notes immediately', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.pollingManager = {
checkIssueNow: jest.fn().mockResolvedValue(undefined),
};
await gitHubImplementation.refreshNotesNow('posts', 'my-post');
expect(gitHubImplementation.pollingManager.checkIssueNow).toHaveBeenCalledWith(
'posts',
'my-post',
);
});
it('should throw error when refreshing without polling manager', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.pollingManager = undefined;
await expect(gitHubImplementation.refreshNotesNow('posts', 'my-post')).rejects.toThrow(
'Polling manager not initialized',
);
});
it('should start polling and store unwatch function', async () => {
const gitHubImplementation = new GitHubImplementation(config);
const unwatchFn = jest.fn();
gitHubImplementation.pollingManager = {
watchIssueWithRetry: jest.fn().mockResolvedValue(unwatchFn),
getStatus: jest.fn().mockReturnValue({ currentWatch: null }),
};
const callbacks = {
onUpdate: jest.fn(),
onChange: jest.fn(),
};
await gitHubImplementation.startNotesPolling('posts', 'my-post', callbacks);
expect(gitHubImplementation.pollingManager.watchIssueWithRetry).toHaveBeenCalledWith(
'posts',
'my-post',
callbacks,
5,
2000,
);
expect(gitHubImplementation.unwatchFunctions.get('posts/my-post')).toBe(unwatchFn);
});
it('should stop existing polling before starting new one', async () => {
const gitHubImplementation = new GitHubImplementation(config);
const oldUnwatchFn = jest.fn();
const newUnwatchFn = jest.fn();
gitHubImplementation.unwatchFunctions.set('posts/my-post', oldUnwatchFn);
gitHubImplementation.pollingManager = {
watchIssueWithRetry: jest.fn().mockResolvedValue(newUnwatchFn),
getStatus: jest.fn().mockReturnValue({ currentWatch: 'posts/other-post' }),
};
const callbacks = { onUpdate: jest.fn() };
await gitHubImplementation.startNotesPolling('posts', 'my-post', callbacks);
expect(oldUnwatchFn).toHaveBeenCalledTimes(1);
expect(gitHubImplementation.unwatchFunctions.get('posts/my-post')).toBe(newUnwatchFn);
});
it('should handle polling manager error gracefully', async () => {
const gitHubImplementation = new GitHubImplementation(config);
gitHubImplementation.pollingManager = {
watchIssueWithRetry: jest.fn().mockRejectedValue(new Error('Failed to find issue')),
getStatus: jest.fn().mockReturnValue({ currentWatch: null }),
};
const callbacks = { onUpdate: jest.fn() };
await gitHubImplementation.startNotesPolling('posts', 'my-post', callbacks);
// Should not throw, just log error
expect(console.error).toHaveBeenCalledWith(
'[DecapNotes Polling] Failed to start polling after retries:',
expect.any(Error),
);
});
});
});
});