-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathentries.test.ts
More file actions
1156 lines (997 loc) · 40.5 KB
/
Copy pathentries.test.ts
File metadata and controls
1156 lines (997 loc) · 40.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
import { expect } from 'chai';
import sinon from 'sinon';
import * as path from 'path';
import { FsUtility, handleAndLogError, messageHandler } from '@contentstack/cli-utilities';
import * as utilities from '@contentstack/cli-utilities';
import EntriesExport from '../../../../src/export/modules/entries';
import ExportConfig from '../../../../src/types/export-config';
import * as variants from '@contentstack/cli-variants';
import * as fsUtilModule from '../../../../src/utils/file-helper';
describe('EntriesExport', () => {
let entriesExport: any;
let mockStackAPIClient: any;
let mockExportConfig: ExportConfig;
let mockFsUtil: any;
let mockExportProjects: any;
let mockVariantEntries: any;
let sandbox: sinon.SinonSandbox;
beforeEach(() => {
sandbox = sinon.createSandbox();
// Mock stack API client
mockStackAPIClient = {
contentType: sandbox.stub(),
};
// Set default return value
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns({
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [],
count: 0,
}),
}),
fetch: sandbox.stub().resolves({}),
}),
});
// Mock ExportConfig
mockExportConfig = {
versioning: false,
host: 'https://api.contentstack.io',
developerHubUrls: {},
apiKey: 'test-api-key',
exportDir: '/test/export',
data: '/test/data',
branchName: '',
context: {
command: 'cm:stacks:export',
module: 'entries',
userId: 'user-123',
email: 'test@example.com',
sessionId: 'session-123',
apiKey: 'test-api-key',
orgId: 'org-123',
authenticationMethod: 'Basic Auth',
},
cliLogsPath: '/test/logs',
forceStopMarketplaceAppsPrompt: false,
master_locale: { code: 'en-us' },
region: {
name: 'us',
cma: 'https://api.contentstack.io',
cda: 'https://cdn.contentstack.io',
uiHost: 'https://app.contentstack.com',
},
skipStackSettings: false,
skipDependencies: false,
languagesCode: ['en'],
apis: {},
preserveStackVersion: false,
personalizationEnabled: false,
fetchConcurrency: 5,
writeConcurrency: 5,
developerHubBaseUrl: '',
marketplaceAppEncryptionKey: '',
modules: {
types: ['entries'],
entries: {
dirName: 'entries',
fileName: 'entries.json',
invalidKeys: ['ACL', '_version'],
limit: 100,
chunkFileSize: 1000,
batchLimit: 5,
exportVersions: false,
},
locales: {
dirName: 'locales',
fileName: 'locales.json',
},
content_types: {
dirName: 'content_types',
fileName: 'content_types.json',
},
personalize: {
baseURL: {
us: 'https://personalize-api.contentstack.com',
'AWS-NA': 'https://personalize-api.contentstack.com',
'AWS-EU': 'https://eu-personalize-api.contentstack.com',
},
dirName: 'personalize',
exportOrder: [],
},
},
org_uid: 'test-org-uid',
query: {},
} as any;
// Mock fsUtil
mockFsUtil = {
readFile: sandbox.stub(),
makeDirectory: sandbox.stub().resolves(),
writeFile: sandbox.stub(),
};
sandbox.stub(fsUtilModule, 'fsUtil').value(mockFsUtil);
// Mock ExportProjects
mockExportProjects = {
init: sandbox.stub().resolves(),
projects: sandbox.stub().resolves([]),
};
sandbox.stub(variants, 'ExportProjects').callsFake(() => mockExportProjects as any);
// Mock VariantEntries
mockVariantEntries = {
exportVariantEntry: sandbox.stub().resolves(),
};
sandbox.stub(variants.Export, 'VariantEntries').callsFake(() => mockVariantEntries as any);
// Mock handleAndLogError - will be replaced in individual tests if needed
// Mock FsUtility - stub methods to avoid directory creation
sandbox.stub(FsUtility.prototype, 'writeIntoFile');
sandbox.stub(FsUtility.prototype, 'completeFile').resolves();
// Stub the createFolderIfNotExist method that FsUtility calls in constructor
// This method is called synchronously, so we need to stub it
const createFolderStub = sandbox.stub(FsUtility.prototype, 'createFolderIfNotExist' as any);
createFolderStub.callsFake(() => {
// Do nothing - prevent actual directory creation
});
// Stub FsUtility.prototype.readdir and readFile for readContentTypeSchemas support
// readContentTypeSchemas creates its own FsUtility instance, so we need to stub the prototype
sandbox.stub(FsUtility.prototype, 'readdir').returns([]);
sandbox.stub(FsUtility.prototype, 'readFile').returns(undefined);
entriesExport = new EntriesExport({
exportConfig: mockExportConfig,
stackAPIClient: mockStackAPIClient,
moduleName: 'entries',
});
});
afterEach(() => {
sandbox.restore();
});
describe('Constructor', () => {
it('should initialize with correct paths and configuration', () => {
expect(entriesExport).to.be.instanceOf(EntriesExport);
expect(entriesExport.exportConfig).to.equal(mockExportConfig);
expect(entriesExport.stackAPIClient).to.equal(mockStackAPIClient);
expect(entriesExport.exportConfig.context.module).to.equal('entries');
expect(entriesExport.exportVariantEntry).to.be.false;
});
it('should set up correct directory paths based on exportConfig', () => {
const expectedEntriesPath = path.resolve(
mockExportConfig.exportDir,
mockExportConfig.branchName || '',
mockExportConfig.modules.entries.dirName,
);
const expectedLocalesPath = path.resolve(
mockExportConfig.exportDir,
mockExportConfig.branchName || '',
mockExportConfig.modules.locales.dirName,
mockExportConfig.modules.locales.fileName,
);
const expectedContentTypesDirPath = path.resolve(
mockExportConfig.exportDir,
mockExportConfig.branchName || '',
mockExportConfig.modules.content_types.dirName,
);
expect(entriesExport.entriesDirPath).to.equal(expectedEntriesPath);
expect(entriesExport.localesFilePath).to.equal(expectedLocalesPath);
expect(entriesExport.contentTypesDirPath).to.equal(expectedContentTypesDirPath);
});
it('should initialize ExportProjects instance', () => {
// Verify projectInstance exists
expect(entriesExport.projectInstance).to.exist;
// The stub intercepts the constructor call, so projectInstance should be the mock
// However, if the actual constructor runs, it will be an ExportProjects instance
// So we just verify it exists and has the expected structure
expect(entriesExport.projectInstance).to.have.property('projects');
});
});
describe('start() method - Early Returns', () => {
it('should return early when no content types are found', async () => {
// Stub mockFsUtil.readFile for locales
mockFsUtil.readFile.returns([{ code: 'en-us' }]);
// Stub FsUtility.prototype for readContentTypeSchemas to return empty
(FsUtility.prototype.readdir as sinon.SinonStub).returns([]); // No content type files
await entriesExport.start();
// Should not attempt to fetch entries
expect(mockStackAPIClient.contentType.called).to.be.false;
// Should read locales file
expect(mockFsUtil.readFile.called).to.be.true;
});
it('should handle empty locales array gracefully', async () => {
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1', schema: [] as any }];
// Stub mockFsUtil.readFile for locales
mockFsUtil.readFile.returns([]); // empty locales
// Stub FsUtility.prototype for readContentTypeSchemas to return content types
(FsUtility.prototype.readdir as sinon.SinonStub).returns(['ct-1.json']);
(FsUtility.prototype.readFile as sinon.SinonStub).returns(contentTypes[0]);
await entriesExport.start();
// Should still process entries with master locale
expect(mockStackAPIClient.contentType.called).to.be.true;
});
it('should handle non-array locales gracefully', async () => {
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1', schema: [] as any }];
// Stub mockFsUtil.readFile for locales
mockFsUtil.readFile.returns([]); // empty locales array
// Stub FsUtility.prototype for readContentTypeSchemas to return content types
(FsUtility.prototype.readdir as sinon.SinonStub).returns(['ct-1.json']);
(FsUtility.prototype.readFile as sinon.SinonStub).returns(contentTypes[0]);
// Mock entry query for when entries are processed
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [],
count: 0,
}),
}),
};
const contentTypeStub = sandbox.stub().returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
// Update both the mock and entriesExport to use the new stub
mockStackAPIClient.contentType = contentTypeStub;
entriesExport.stackAPIClient = mockStackAPIClient;
await entriesExport.start();
// Should still process entries with master locale (createRequestObjects uses master locale when locales is empty)
expect(contentTypeStub.called).to.be.true;
});
});
describe('start() method - Personalization and Variant Entries', () => {
it('should enable variant entry export when personalization is enabled and project is found', async () => {
mockExportConfig.personalizationEnabled = true;
entriesExport.exportConfig.personalizationEnabled = true;
const project = [{ uid: 'project-123' }];
// Ensure projectInstance is the mock so projects() returns the expected value
entriesExport.projectInstance = mockExportProjects;
mockExportProjects.projects.resolves(project);
const locales = [{ code: 'en-us' }];
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1' }];
mockFsUtil.readFile.onFirstCall().returns(locales).onSecondCall().returns(contentTypes);
// Mock successful entry fetch - use callsFake to preserve call tracking
const contentTypeStub = sandbox.stub().returns({
entry: sandbox.stub().returns({
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [],
count: 0,
}),
}),
}),
});
mockStackAPIClient.contentType = contentTypeStub;
// Update entriesExport to use the new mock
entriesExport.stackAPIClient = mockStackAPIClient;
await entriesExport.start();
// Should check for projects
// Note: projectInstance is created in constructor, so we need to check if it was called
// The actual call happens in start() method, so we verify the behavior instead
// If exportVariantEntry is true, it means projects() was called and returned a project
// Should enable variant entry export
expect(entriesExport.exportVariantEntry).to.be.true;
// Should initialize VariantEntries with project_id
const variantEntriesStub = variants.Export.VariantEntries as unknown as sinon.SinonStub;
expect(variantEntriesStub.called).to.be.true;
expect(variantEntriesStub.firstCall.args[0]).to.include({
project_id: 'project-123',
});
// Verify the flow completed successfully
// The key behavior is that exportVariantEntry is enabled when project is found
expect(entriesExport.exportVariantEntry).to.be.true;
// Verify that start() completed without throwing errors
// This confirms that the entire flow executed, including processing entries
});
it('should not enable variant entry export when personalization is enabled but no project is found', async () => {
mockExportConfig.personalizationEnabled = true;
entriesExport.exportConfig.personalizationEnabled = true;
mockExportProjects.init.resolves();
mockExportProjects.projects.resolves([]);
const locales = [{ code: 'en-us' }];
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1' }];
mockFsUtil.readFile.onFirstCall().returns(locales).onSecondCall().returns(contentTypes);
const contentTypeStub = sandbox.stub().returns({
entry: sandbox.stub().returns({
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [],
count: 0,
}),
}),
}),
});
mockStackAPIClient.contentType = contentTypeStub;
// Update entriesExport to use the new mock
entriesExport.stackAPIClient = mockStackAPIClient;
await entriesExport.start();
// Should not enable variant entry export
// If exportVariantEntry is false, it means either projects() wasn't called,
// or it returned an empty array, or no project was found
expect(entriesExport.exportVariantEntry).to.be.false;
// Verify the flow completed successfully
// The key behavior is that exportVariantEntry is NOT enabled when no project is found
expect(entriesExport.exportVariantEntry).to.be.false;
// Verify that start() completed without throwing errors
// This confirms that the entire flow executed, including processing entries
});
it('should handle errors when fetching projects gracefully', async () => {
mockExportConfig.personalizationEnabled = true;
entriesExport.exportConfig.personalizationEnabled = true;
const projectError = new Error('Project fetch failed');
mockExportProjects.init.resolves();
mockExportProjects.projects.rejects(projectError);
const handleAndLogErrorSpy = sandbox.spy();
try {
sandbox.replaceGetter(utilities, 'handleAndLogError', () => handleAndLogErrorSpy);
} catch (e) {
// Already replaced, restore first
sandbox.restore();
sandbox.replaceGetter(utilities, 'handleAndLogError', () => handleAndLogErrorSpy);
}
const locales = [{ code: 'en-us' }];
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1' }];
mockFsUtil.readFile.onFirstCall().returns(locales).onSecondCall().returns(contentTypes);
const contentTypeStub = sandbox.stub().returns({
entry: sandbox.stub().returns({
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [],
count: 0,
}),
}),
}),
});
mockStackAPIClient.contentType = contentTypeStub;
// Update entriesExport to use the new mock
entriesExport.stackAPIClient = mockStackAPIClient;
await entriesExport.start();
// Should not enable variant entry export (error occurred, so no project was set)
expect(entriesExport.exportVariantEntry).to.be.false;
// Should handle error - verify error was logged
// Note: handleAndLogError might be called, but we verify the behavior (exportVariantEntry is false)
// which confirms the error was handled and processing continued
// Verify the flow completed successfully despite the error
// The key behavior is that exportVariantEntry is NOT enabled when project fetch fails
expect(entriesExport.exportVariantEntry).to.be.false;
// Verify that start() completed without throwing errors (error was handled)
// This confirms that the entire flow executed, including processing entries
});
});
describe('createRequestObjects() method', () => {
it('should create request objects for each content type and locale combination', () => {
const locales = [{ code: 'en-us' }, { code: 'fr-fr' }];
const contentTypes = [
{ uid: 'ct-1', title: 'Content Type 1' },
{ uid: 'ct-2', title: 'Content Type 2' },
];
const requestObjects = entriesExport.createRequestObjects(locales, contentTypes);
// Should create: (2 locales + 1 master) * 2 content types = 6 request objects
// But actually: 2 content types * (2 locales + 1 master) = 6
expect(requestObjects).to.have.length(6);
expect(requestObjects).to.deep.include({
contentType: 'ct-1',
locale: 'en-us',
});
expect(requestObjects).to.deep.include({
contentType: 'ct-1',
locale: 'fr-fr',
});
expect(requestObjects).to.deep.include({
contentType: 'ct-1',
locale: mockExportConfig.master_locale.code,
});
expect(requestObjects).to.deep.include({
contentType: 'ct-2',
locale: 'en-us',
});
});
it('should return empty array when no content types are provided', () => {
const locales = [{ code: 'en-us' }];
const contentTypes: any[] = [];
const requestObjects = entriesExport.createRequestObjects(locales, contentTypes);
expect(requestObjects).to.be.an('array').that.is.empty;
});
it('should use master locale only when locales array is empty', () => {
const locales: any[] = [];
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1' }];
const requestObjects = entriesExport.createRequestObjects(locales, contentTypes);
// Should create 1 request object with master locale only
expect(requestObjects).to.have.length(1);
expect(requestObjects[0]).to.deep.equal({
contentType: 'ct-1',
locale: mockExportConfig.master_locale.code,
});
});
it('should use master locale only when locales is not an array', () => {
const locales = {} as any;
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1' }];
const requestObjects = entriesExport.createRequestObjects(locales, contentTypes);
// Should create 1 request object with master locale only
expect(requestObjects).to.have.length(1);
expect(requestObjects[0].locale).to.equal(mockExportConfig.master_locale.code);
});
it('should always include master locale for each content type', () => {
const locales = [{ code: 'de-de' }];
const contentTypes = [{ uid: 'ct-1', title: 'Content Type 1' }];
const requestObjects = entriesExport.createRequestObjects(locales, contentTypes);
// Should have 2 objects: one for de-de and one for master locale
expect(requestObjects).to.have.length(2);
const masterLocaleObjects = requestObjects.filter(
(obj: any) => obj.locale === mockExportConfig.master_locale.code,
);
expect(masterLocaleObjects).to.have.length(1);
});
});
describe('getEntries() method - Basic Functionality', () => {
it('should fetch entries and create directory structure on first call', async () => {
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [
{ uid: 'entry-1', title: 'Entry 1' },
{ uid: 'entry-2', title: 'Entry 2' },
],
count: 2,
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
await entriesExport.getEntries(options);
// Should create directory
const expectedPath = path.join(entriesExport.entriesDirPath, 'ct-1', 'en-us');
expect(mockFsUtil.makeDirectory.called).to.be.true;
expect(mockFsUtil.makeDirectory.calledWith(expectedPath)).to.be.true;
// Should initialize FsUtility
expect(entriesExport.entriesFileHelper).to.be.instanceOf(FsUtility);
// Should write entries to file
expect((FsUtility.prototype.writeIntoFile as sinon.SinonStub).called).to.be.true;
expect((FsUtility.prototype.writeIntoFile as sinon.SinonStub).calledWith(sinon.match.array, { mapKeyVal: true }))
.to.be.true;
// Should query with correct parameters
expect(mockEntryQuery.query.called).to.be.true;
});
it('should not create directory on subsequent pagination calls', async () => {
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
// Initialize FsUtility on first call
entriesExport.entriesFileHelper = new FsUtility({
moduleName: 'entries',
indexFileName: 'index.json',
basePath: '/test/path',
chunkFileSize: 1000,
keepMetadata: false,
omitKeys: [],
});
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [{ uid: 'entry-1' }],
count: 150, // More than limit, will paginate
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
// First call
await entriesExport.getEntries({ ...options, skip: 0 });
const firstCallMakeDirCount = mockFsUtil.makeDirectory.callCount;
// Second call (pagination)
await entriesExport.getEntries({ ...options, skip: 100 });
const secondCallMakeDirCount = mockFsUtil.makeDirectory.callCount;
// Should not create directory again on pagination
expect(secondCallMakeDirCount).to.equal(firstCallMakeDirCount);
});
it('should handle pagination correctly when entries exceed limit', async () => {
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
let callCount = 0;
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().callsFake(() => {
callCount++;
if (callCount === 1) {
return Promise.resolve({
items: Array(100)
.fill(null)
.map((_, i) => ({ uid: `entry-${i}` })),
count: 250, // Total entries
});
} else if (callCount === 2) {
return Promise.resolve({
items: Array(100)
.fill(null)
.map((_, i) => ({ uid: `entry-${100 + i}` })),
count: 250,
});
} else {
return Promise.resolve({
items: Array(50)
.fill(null)
.map((_, i) => ({ uid: `entry-${200 + i}` })),
count: 250,
});
}
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
await entriesExport.getEntries(options);
// Should make 3 calls for pagination (100 + 100 + 50 = 250 entries)
expect(mockEntryQuery.query.calledThrice).to.be.true;
// Should write entries 3 times
expect((FsUtility.prototype.writeIntoFile as sinon.SinonStub).calledThrice).to.be.true;
});
it('should return early when no entries are found', async () => {
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [],
count: 0,
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
await entriesExport.getEntries(options);
// Should not create directory or initialize FsUtility
expect(mockFsUtil.makeDirectory.called).to.be.false;
expect(entriesExport.entriesFileHelper).to.be.undefined;
// Should not write to file
expect((FsUtility.prototype.writeIntoFile as sinon.SinonStub).called).to.be.false;
});
it('should handle API errors and propagate them', async () => {
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
const apiError = new Error('API Error');
const handleAndLogErrorSpy = sandbox.spy();
try {
sandbox.replaceGetter(utilities, 'handleAndLogError', () => handleAndLogErrorSpy);
} catch (e) {
// Already replaced, restore first
sandbox.restore();
sandbox.replaceGetter(utilities, 'handleAndLogError', () => handleAndLogErrorSpy);
}
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().rejects(apiError),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
try {
await entriesExport.getEntries(options);
expect.fail('Should have thrown error');
} catch (error) {
expect(error).to.equal(apiError);
// Should handle and log error with context
expect(handleAndLogErrorSpy.called).to.be.true;
expect(handleAndLogErrorSpy.calledWith(apiError, sinon.match.has('contentType', 'ct-1'))).to.be.true;
expect(handleAndLogErrorSpy.getCall(0).args[1]).to.include({
locale: 'en-us',
contentType: 'ct-1',
});
}
});
});
describe('getEntries() method - Version Export', () => {
beforeEach(() => {
mockExportConfig.modules.entries.exportVersions = true;
entriesExport = new EntriesExport({
exportConfig: mockExportConfig,
stackAPIClient: mockStackAPIClient,
moduleName: 'entries',
});
});
it('should export versions when exportVersions is enabled', async () => {
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
const entries = [
{ uid: 'entry-1', _version: 3 },
{ uid: 'entry-2', _version: 2 },
];
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: entries,
count: 2,
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
// Stub fetchEntriesVersions
sandbox.stub(entriesExport, 'fetchEntriesVersions').resolves();
await entriesExport.getEntries(options);
// Should call fetchEntriesVersions with entries
expect((entriesExport.fetchEntriesVersions as sinon.SinonStub).called).to.be.true;
expect(
(entriesExport.fetchEntriesVersions as sinon.SinonStub).calledWith(
entries,
sinon.match({
locale: 'en-us',
contentType: 'ct-1',
versionedEntryPath: sinon.match.string,
}),
),
).to.be.true;
// Should create versions directory
expect(mockFsUtil.makeDirectory.called).to.be.true;
const makeDirCalls = mockFsUtil.makeDirectory.getCalls();
const versionsCall = makeDirCalls.find((call: any) => call.args[0].includes('versions'));
expect(versionsCall).to.exist;
});
it('should not export versions when exportVersions is disabled', async () => {
mockExportConfig.modules.entries.exportVersions = false;
entriesExport = new EntriesExport({
exportConfig: mockExportConfig,
stackAPIClient: mockStackAPIClient,
moduleName: 'entries',
});
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [{ uid: 'entry-1' }],
count: 1,
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
sandbox.stub(entriesExport, 'fetchEntriesVersions').resolves();
await entriesExport.getEntries(options);
// Should not call fetchEntriesVersions
expect((entriesExport.fetchEntriesVersions as sinon.SinonStub).called).to.be.false;
});
});
describe('getEntries() method - Variant Entry Export', () => {
it('should export variant entries when exportVariantEntry is enabled', async () => {
entriesExport.exportVariantEntry = true;
entriesExport.variantEntries = mockVariantEntries;
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
const entries = [
{ uid: 'entry-1', title: 'Entry 1' },
{ uid: 'entry-2', title: 'Entry 2' },
];
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: entries,
count: 2,
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
await entriesExport.getEntries(options);
// Should call exportVariantEntry with correct parameters
expect(mockVariantEntries.exportVariantEntry.called).to.be.true;
expect(
mockVariantEntries.exportVariantEntry.calledWith({
locale: 'en-us',
contentTypeUid: 'ct-1',
entries: entries,
}),
).to.be.true;
});
it('should not export variant entries when exportVariantEntry is disabled', async () => {
entriesExport.exportVariantEntry = false;
const options = {
contentType: 'ct-1',
locale: 'en-us',
skip: 0,
};
const mockEntryQuery = {
query: sandbox.stub().returns({
find: sandbox.stub().resolves({
items: [{ uid: 'entry-1' }],
count: 1,
}),
}),
};
mockStackAPIClient.contentType.returns({
entry: sandbox.stub().returns(mockEntryQuery),
});
await entriesExport.getEntries(options);
// Should not call exportVariantEntry
if (entriesExport.variantEntries) {
expect(mockVariantEntries.exportVariantEntry.called).to.be.false;
}
});
});
describe('fetchEntriesVersions() method', () => {
it('should process entries through makeConcurrentCall with correct configuration', async () => {
const entries = [
{ uid: 'entry-1', _version: 2 },
{ uid: 'entry-2', _version: 1 },
];
const options = {
locale: 'en-us',
contentType: 'ct-1',
versionedEntryPath: '/test/versions',
};
// Stub makeConcurrentCall
const makeConcurrentCallStub = sandbox.stub(entriesExport, 'makeConcurrentCall').resolves();
await entriesExport.fetchEntriesVersions(entries, options);
// Should call makeConcurrentCall with correct configuration
expect(makeConcurrentCallStub.calledOnce).to.be.true;
const callArgs = makeConcurrentCallStub.getCall(0).args[0];
expect(callArgs.module).to.equal('versioned-entries');
expect(callArgs.apiBatches).to.deep.equal([entries]);
expect(callArgs.totalCount).to.equal(entries.length);
expect(callArgs.concurrencyLimit).to.equal(mockExportConfig.modules.entries.batchLimit);
expect(callArgs.apiParams.module).to.equal('versioned-entries');
expect(callArgs.apiParams.queryParam).to.deep.equal(options);
expect(callArgs.apiParams.resolve).to.be.a('function');
expect(callArgs.apiParams.reject).to.be.a('function');
// Should pass entryVersionHandler as the handler
expect(makeConcurrentCallStub.getCall(0).args[1]).to.be.a('function');
});
});
describe('entryVersionHandler() method', () => {
it('should successfully fetch and resolve entry versions', async () => {
const entry = { uid: 'entry-1', _version: 2 };
const apiParams = {
module: 'versioned-entries',
queryParam: {
locale: 'en-us',
contentType: 'ct-1',
},
resolve: sandbox.spy(),
reject: sandbox.spy(),
};
const versions = [
{ uid: 'entry-1', _version: 1 },
{ uid: 'entry-1', _version: 2 },
];
sandbox.stub(entriesExport, 'getEntryByVersion').resolves(versions);
await entriesExport.entryVersionHandler({
apiParams: apiParams as any,
element: entry,
isLastRequest: false,
});
// Should call getEntryByVersion
expect((entriesExport.getEntryByVersion as sinon.SinonStub).called).to.be.true;
expect((entriesExport.getEntryByVersion as sinon.SinonStub).calledWith(apiParams.queryParam, entry)).to.be.true;
// Should call resolve with correct data
expect(apiParams.resolve.called).to.be.true;
expect(
apiParams.resolve.calledWith({
response: versions,
apiData: entry,
}),
).to.be.true;
// Should not call reject
expect(apiParams.reject.called).to.be.false;
});
it('should handle errors and call reject callback', async () => {
const entry = { uid: 'entry-1', _version: 2 };
const apiParams = {
module: 'versioned-entries',
queryParam: {
locale: 'en-us',
contentType: 'ct-1',
},
resolve: sandbox.spy(),
reject: sandbox.spy(),
};
const versionError = new Error('Version fetch failed');
sandbox.stub(entriesExport, 'getEntryByVersion').rejects(versionError);
// The handler rejects with true, so we need to catch it
try {
await entriesExport.entryVersionHandler({
apiParams: apiParams as any,
element: entry,
isLastRequest: false,
});
} catch (error) {
// Expected - the handler rejects with true
expect(error).to.be.true;
}
// Should call reject with error
expect(apiParams.reject.called).to.be.true;
expect(
apiParams.reject.calledWith({
error: versionError,
apiData: entry,
}),
).to.be.true;
// Should not call resolve
expect(apiParams.resolve.called).to.be.false;
});
});
describe('getEntryByVersion() method', () => {
it('should recursively fetch all versions of an entry', async () => {
const entry = { uid: 'entry-1', _version: 3 };
const options = {
locale: 'en-us',
contentType: 'ct-1',
};
let versionCallCount = 0;
const mockEntryFetch = sandbox.stub().callsFake(() => {
versionCallCount++;
return Promise.resolve({
uid: 'entry-1',
_version: 4 - versionCallCount, // 3, 2, 1
});
});
const mockEntryMethod = sandbox.stub().callsFake((uid: string) => ({
fetch: mockEntryFetch,
}));
mockStackAPIClient.contentType.returns({
entry: mockEntryMethod,
});
const versions = await entriesExport.getEntryByVersion(options, entry);
// Should fetch 3 versions (3, 2, 1)
expect(mockEntryFetch.calledThrice).to.be.true;
expect(versions).to.have.length(3);
// Should fetch with correct version numbers
expect(mockEntryFetch.getCall(0).args[0]).to.deep.include({
version: 3,
locale: 'en-us',
});
});