-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathFSXARemoteApi.spec.ts
More file actions
1036 lines (1009 loc) · 41.6 KB
/
FSXARemoteApi.spec.ts
File metadata and controls
1036 lines (1009 loc) · 41.6 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 { faker } from '@faker-js/faker'
import { FSXAApiErrors, FSXAContentMode, HttpStatus } from '../enums'
import { FetchResponse, QueryBuilderQuery, SortParams } from '../types'
import { FSXARemoteApi } from './FSXARemoteApi'
import {
ArrayQueryOperatorEnum,
ComparisonQueryOperatorEnum,
} from './QueryBuilder'
import { generateRandomConfig } from '../testutils/generateRandomConfig'
import 'jest-fetch-mock'
import {
createDataEntry,
createMediaPicture,
createMediaPictureReference,
} from '../testutils'
import { getMappedMediaPicture } from '../testutils/getMappedMediaPicture'
require('jest-fetch-mock').enableFetchMocks()
describe('FSXARemoteAPI', () => {
beforeEach(() => {
fetchMock.resetMocks()
})
describe('The initialization', () => {
let config: any
let remoteApi: FSXARemoteApi
beforeEach(() => {
config = generateRandomConfig()
})
it('should get initialized', () => {
remoteApi = new FSXARemoteApi(config)
expect(remoteApi).not.toBeNull()
})
it('should throw an error if the API_KEY is not set', () => {
delete config.apikey
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.MISSING_API_KEY)
})
it('should throw an error if the CAAS_URL is not set', () => {
delete config.caasURL
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.MISSING_CAAS_URL)
})
it('should throw an error if the NAVIGATION_SERVICE_URL is not set', () => {
delete config.navigationServiceURL
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.MISSING_NAVIGATION_SERVICE_URL)
})
it('should throw an error if the PROJECT_ID is not set', () => {
delete config.projectID
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.MISSING_PROJECT_ID)
})
it('should throw an error if the TENANT_ID is not set', () => {
delete config.tenantID
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.MISSING_TENANT_ID)
})
it('should throw an error if remotes are provided without id', () => {
delete config.remotes.remote.id
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.MISSING_REMOTE_ID)
})
it('should throw an error if remotes are provided without locale', () => {
delete config.remotes.remote.locale
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.MISSING_REMOTE_LOCALE)
})
it('should throw an error if contentMode is not set', () => {
delete config.contentMode
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.UNKNOWN_CONTENT_MODE)
})
it('should throw an error if an invalid content mode is set', () => {
config.contentMode = faker.string.alpha()
expect(() => {
new FSXARemoteApi(config)
}).toThrow(FSXAApiErrors.UNKNOWN_CONTENT_MODE)
})
})
describe('buildAuthorizationHeaders', () => {
it('should return the correct authorization object', () => {
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualAuthorizationHeaders = remoteApi.authorizationHeader
const expectedAuthorizationHeaders = {
authorization: `Bearer ${config.apikey}`,
}
expect(actualAuthorizationHeaders).toStrictEqual(
expectedAuthorizationHeaders
)
})
})
describe('buildCaaSUrl', () => {
it('should return the correct caas url', () => {
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl()
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url for a remote project', () => {
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const remoteProjectId = config.remotes.remote.id
const actualCaaSUrl = remoteApi.buildCaaSUrl({
remoteProject: remoteProjectId,
})
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${remoteProjectId}.${config.contentMode}.content`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should use the remote contentMode if provided', () => {
const config = generateRandomConfig()
const remoteProjectId = config.remotes.remote.id
config.contentMode = FSXAContentMode.RELEASE
;(config.remotes.remote as any).contentMode = FSXAContentMode.PREVIEW
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({
remoteProject: remoteProjectId,
})
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${remoteProjectId}.preview.content`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url with a locale but no id', () => {
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({ locale })
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when an id is set', () => {
const id = faker.string.uuid()
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({ id })
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content/${id}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when additionalParameter are set', () => {
const value = { firstValue: 1, secondValue: 1 }
const additionalParams = { keys: value }
const encodedValue = encodeURIComponent(JSON.stringify(value))
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({ additionalParams })
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?keys=${encodedValue}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when id, locale and additionalParameter are set', () => {
const id = faker.string.uuid()
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const keysValue = { firstValue: 1, secondValue: 1 }
const sortValue = { firstName: 1 }
const additionalParams = { keys: keysValue, sort: sortValue }
const encodedKeysValue = encodeURIComponent(
JSON.stringify({ firstValue: 1, secondValue: 1 })
)
const encodedSortValue = encodeURIComponent(
JSON.stringify({ firstName: 1 })
)
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({
id,
locale,
additionalParams,
})
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content/${id}.${locale}?keys=${encodedKeysValue}&sort=${encodedSortValue}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when filters are set', () => {
const firstValue = faker.lorem.word()
const secondValue = faker.lorem.word()
const firstField = faker.lorem.word()
const secondField = faker.lorem.word()
const firstOperator = ComparisonQueryOperatorEnum.EQUALS
const secondOperator = ComparisonQueryOperatorEnum.EQUALS
const filters: QueryBuilderQuery[] = [
{
value: firstValue,
field: firstField,
operator: firstOperator,
},
{
value: secondValue,
field: secondField,
operator: secondOperator,
},
]
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({ filters })
const encodedFirstFilterValue = encodeURIComponent(
`{"${firstField}":{"${firstOperator}":"${firstValue}"}}`
)
const encodedSecondFilterValue = encodeURIComponent(
`{"${secondField}":{"${secondOperator}":"${secondValue}"}}`
)
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?filter=${encodedFirstFilterValue}&filter=${encodedSecondFilterValue}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when filters and additionalParams are set', () => {
const filterField = faker.lorem.word()
const filterValue = faker.lorem.word()
const filterOperator = ComparisonQueryOperatorEnum.EQUALS
const filters: QueryBuilderQuery[] = [
{
value: filterValue,
field: filterField,
operator: filterOperator,
},
]
const additionalParams = {
keys: {
identifier: 1,
},
}
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({
filters,
additionalParams,
})
const encodedAdditionalParamsValue =
encodeURIComponent(`{"identifier":1}`)
const encodedFilterValue = encodeURIComponent(
`{"${filterField}":{"${filterOperator}":"${filterValue}"}}`
)
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?keys=${encodedAdditionalParamsValue}&filter=${encodedFilterValue}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when filters and complex additionalParams are set', () => {
const filterField = faker.lorem.word()
const filterValue = faker.lorem.word()
const filterOperator = ComparisonQueryOperatorEnum.EQUALS
const filters: QueryBuilderQuery[] = [
{
value: filterValue,
field: filterField,
operator: filterOperator,
},
]
const additionalParams = {
keys: {
identifier: 1,
},
filter: [
{ schema: 'newsroom' },
{ entityType: { $in: ['item', 'type'] } },
],
}
const firstEncodedParamsValue = encodeURIComponent(
JSON.stringify({ identifier: 1 })
)
const secondEncodedParamsValue = encodeURIComponent(
JSON.stringify({ schema: 'newsroom' })
)
const thirdEncodedParamsValue = encodeURIComponent(
JSON.stringify({ entityType: { $in: ['item', 'type'] } })
)
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({
filters,
additionalParams,
})
const additionalParamsQuery = `keys=${firstEncodedParamsValue}&filter=${secondEncodedParamsValue}&filter=${thirdEncodedParamsValue}`
const encodedFilterValue = encodeURIComponent(
`{"${filterField}":{"${filterOperator}":"${filterValue}"}}`
)
const filterQuery = `filter=${encodedFilterValue}`
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?${additionalParamsQuery}&${filterQuery}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when page is set', () => {
const page = faker.number.int()
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({ page })
const pageQuery = `page=${page}`
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?${pageQuery}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when pagesize is set', () => {
const pagesize = faker.number.int()
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({ pagesize })
const pagesizeQuery = `pagesize=${pagesize}`
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?${pagesizeQuery}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should throw an error for an invalid remote project', () => {
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
try {
remoteApi.buildCaaSUrl({ remoteProject: 'unknown project' })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.UNKNOWN_REMOTE)
expect(error.statusCode).toBe(HttpStatus.NOT_FOUND)
}
})
it('should return the correct caas url when special chars are used in id, locale, page or pagesize', () => {
const specialChars = "*_'();:@&=+$,?%#[]_*'();:@&=+$,?%#[]"
const id = specialChars
const locale = specialChars
const page = specialChars
const pagesize = specialChars
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({
id,
locale,
// @ts-ignore
page,
// @ts-ignore
pagesize,
})
const encodedId = encodeURIComponent(id)
const encodedLocale = encodeURIComponent(locale)
const encodedPage = encodeURIComponent(page)
const encodedPagesize = encodeURIComponent(pagesize)
const baseURL = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content/`
const expectedCaaSUrl = `${baseURL}${encodedId}.${encodedLocale}?page=${encodedPage}&pagesize=${encodedPagesize}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when special chars are used in additionalParams', () => {
const specialChars = "*_'();:@&=+$,?%#[]_*'();:@&=+$,?%#[]"
const additionalParams = {
[specialChars]: [
{ [specialChars]: specialChars },
{ [specialChars]: specialChars },
],
}
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({
additionalParams,
})
const encodedKey = encodeURIComponent(`${specialChars}`)
const encodedValue = encodeURIComponent(
JSON.stringify({ [specialChars]: specialChars })
)
const expectedCaaSUrl = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?${encodedKey}=${encodedValue}&${encodedKey}=${encodedValue}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should return the correct caas url when special chars are used in filters or sort', () => {
const specialChars = "*_'();:@&=+$,?%#[]_*'();:@&=+$,?%#[]"
const locale = specialChars
const filterOperator = ComparisonQueryOperatorEnum.EQUALS
const filters: QueryBuilderQuery[] = [
{
value: `firstVal${specialChars}`,
field: `firstField${specialChars}`,
operator: filterOperator,
},
{
value: `secondVal${specialChars}`,
field: `secondField${specialChars}`,
operator: filterOperator,
},
]
const sort: SortParams[] = [
{ name: specialChars, order: 'desc' },
{ name: specialChars, order: 'asc' },
]
const config = generateRandomConfig()
const remoteApi = new FSXARemoteApi(config)
const actualCaaSUrl = remoteApi.buildCaaSUrl({
locale,
filters,
sort,
})
const firstEncodedFilter = encodeURIComponent(
`{"${`firstField${specialChars}`}":{"${filterOperator}":"${`firstVal${specialChars}`}"}}`
)
const secondEncodedFilter = encodeURIComponent(
`{"${`secondField${specialChars}`}":{"${filterOperator}":"${`secondVal${specialChars}`}"}}`
)
const thirdEncodedFilter = encodeURIComponent(
`{"locale.language":{"${filterOperator}":"${
specialChars.split('_')[0]
}"}}`
)
const fourthEncodedFilter = encodeURIComponent(
`{"locale.country":{"${filterOperator}":"${
specialChars.split('_')[1]
}"}}`
)
const encodedSortName = encodeURIComponent(specialChars)
const encodedSort = `sort=-${encodedSortName}&sort=${encodedSortName}`
const baseURL = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content`
const expectedCaaSUrl = `${baseURL}?filter=${firstEncodedFilter}&filter=${secondEncodedFilter}&filter=${thirdEncodedFilter}&filter=${fourthEncodedFilter}&${encodedSort}`
expect(actualCaaSUrl).toStrictEqual(expectedCaaSUrl)
})
it('should thrown an error when invalid locale is passed', () => {
const locale = 'invalidlocale'
const config = generateRandomConfig()
const filters: QueryBuilderQuery[] = [
{
value: faker.lorem.word(),
field: faker.lorem.word(),
operator: ComparisonQueryOperatorEnum.EQUALS,
},
]
const remoteApi = new FSXARemoteApi(config)
try {
remoteApi.buildCaaSUrl({ filters, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.INVALID_LOCALE)
expect(error.statusCode).toBe(HttpStatus.BAD_REQUEST)
}
})
})
describe('buildNavigationServiceUrl', () => {
let remoteApi: FSXARemoteApi
let config
beforeEach(() => {
config = generateRandomConfig()
remoteApi = new FSXARemoteApi(config)
})
it('should return a correct url', () => {
const correctURL =
/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/g
const navigationServiceApi = remoteApi.buildNavigationServiceUrl()
expect(correctURL.test(navigationServiceApi)).toBe(true)
})
it('should return a correct url when passing the locale', () => {
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const actualNavigationSericeUrl = remoteApi.buildNavigationServiceUrl({
locale,
})
const expectedEndOfNavigationServiceUrl = `?depth=99&format=caas&language=${locale}`
expect(
actualNavigationSericeUrl.endsWith(expectedEndOfNavigationServiceUrl)
).toBe(true)
})
it('should return a correct url when passing the initialPath', () => {
const initialPath = faker.lorem.words(3).split(' ').join('/')
const actualNavigationSericeUrl = remoteApi.buildNavigationServiceUrl({
initialPath,
})
const expectedEndOfNavigationServiceUrl = `/by-seo-route/${initialPath}?depth=99&format=caas`
expect(
actualNavigationSericeUrl.endsWith(expectedEndOfNavigationServiceUrl)
).toBe(true)
})
it('should not return the seo-route url when initialPath is /', () => {
const initialPath = '/'
const actualNavigationSericeUrl = remoteApi.buildNavigationServiceUrl({
initialPath,
})
const expectedEndOfNavigationServiceUrl = `/by-seo-route/${initialPath}?depth=99&format=caas&all`
expect(
actualNavigationSericeUrl.endsWith(expectedEndOfNavigationServiceUrl)
).not.toBe(true)
})
})
describe('fetchElement', () => {
let remoteApi: FSXARemoteApi
let config: any
let uuid: string
let locale: string
beforeEach(() => {
uuid = faker.string.uuid()
locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase().toUpperCase()}`
config = generateRandomConfig()
remoteApi = new FSXARemoteApi(config)
})
it('should call fetchByFilter internally', async () => {
const data = createDataEntry()
fetchMock.mockResponseOnce(JSON.stringify(data))
remoteApi.fetchByFilter = jest.fn().mockResolvedValue({
page: 1,
pagesize: 1,
items: ['myItem'] as any,
} as FetchResponse)
await remoteApi.fetchElement({
id: data.identifier,
locale,
fetchOptions: {},
additionalParams: {},
filterContext: {},
})
expect(remoteApi.fetchByFilter).toHaveBeenCalledTimes(1)
expect(remoteApi.fetchByFilter).toHaveBeenCalledWith({
filters: [
{
operator: ComparisonQueryOperatorEnum.EQUALS,
field: 'identifier',
value: data.identifier,
},
],
additionalParams: {},
fetchOptions: {},
filterContext: {},
normalized: true,
remoteProject: undefined,
locale,
})
})
it('should throw a not found error when the response is 404', async () => {
remoteApi.fetchByFilter = jest
.fn()
.mockResolvedValue({ page: 1, pagesize: 1, items: [] } as FetchResponse)
try {
await remoteApi.fetchElement({ id: uuid, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.NOT_FOUND)
expect(error.statusCode).toBe(HttpStatus.NOT_FOUND)
}
})
it('should throw an unauthorized error when the response is 401', async () => {
fetchMock.mockResponseOnce('', { status: HttpStatus.UNAUTHORIZED })
try {
await remoteApi.fetchElement({ id: uuid, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.NOT_AUTHORIZED)
expect(error.statusCode).toBe(HttpStatus.UNAUTHORIZED)
}
})
it('should throw an unknown error with status 400 when the response is not ok', async () => {
fetchMock.mockResponseOnce('', { status: HttpStatus.BAD_REQUEST })
try {
await remoteApi.fetchElement({ id: uuid, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.UNKNOWN_ERROR)
expect(error.statusCode).toBe(HttpStatus.BAD_REQUEST)
}
})
it('should return the response', async () => {
const caasApiItem = createDataEntry()
const mockRes = {
_embedded: {
'rh:doc': [caasApiItem],
},
}
fetchMock.mockResponse(JSON.stringify(mockRes))
const actualRequest = await remoteApi.fetchElement({ id: uuid, locale })
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual(caasApiItem)
})
it('should return a mapped response when additionalParams are set', async () => {
const item = createDataEntry()
const mockRes = {
_embedded: {
'rh:doc': [item],
},
}
fetchMock.mockResponse(JSON.stringify(mockRes))
const actualRequest = await remoteApi.fetchElement({
id: uuid,
locale,
additionalParams: { depth: 99 },
})
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual(item)
})
})
describe('fetchByFilter', () => {
let remoteApi: FSXARemoteApi
let config: ReturnType<typeof generateRandomConfig>
let filters: QueryBuilderQuery[]
let filterValue: string
let filterField: string
let localeLanguage: string
let localeCountry: string
let locale: string
let json: Record<string, any>
beforeEach(() => {
filterValue = faker.lorem.word()
filterField = faker.lorem.word()
filters = [
{
value: filterValue,
field: filterField,
operator: ComparisonQueryOperatorEnum.EQUALS,
},
]
localeLanguage = faker.lorem.word(2).toLowerCase()
localeCountry = faker.lorem.word(2).toUpperCase()
locale = localeLanguage + '_' + localeCountry
config = generateRandomConfig()
remoteApi = new FSXARemoteApi(config)
json = {
_embedded: {
'rh:doc': faker.helpers.multiple(() => faker.lorem.word()),
},
}
})
it('should trigger the fetch method with the correct params', async () => {
fetchMock.mockResponseOnce(JSON.stringify(json))
await remoteApi.fetchByFilter({ filters, locale })
const actualURL = fetchMock.mock.calls[0][0]
const firstEncodedFilterValue = encodeURIComponent(
`{"${filterField}":{"$eq":"${filterValue}"}}`
)
const secondEncodedFilterValue = encodeURIComponent(
`{"locale.language":{"$eq":"${localeLanguage}"}}`
)
const thirdEncodedFilterValue = encodeURIComponent(
`{"locale.country":{"$eq":"${localeCountry}"}}`
)
const expectedURL = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?rep=hal&filter=${firstEncodedFilterValue}&filter=${secondEncodedFilterValue}&filter=${thirdEncodedFilterValue}&page=1&pagesize=30`
expect(actualURL).toBe(expectedURL)
})
it('should trigger the fetch method with the sort param', async () => {
fetchMock.mockResponseOnce(JSON.stringify(json))
const sort = [
{ name: 'displayName', order: 'asc' },
{ name: 'template.name', order: 'desc' },
] as SortParams[]
await remoteApi.fetchByFilter({ filters, locale, sort })
const actualURL = fetchMock.mock.calls[0][0]
const firstEncodedFilterValue = encodeURIComponent(
`{"${filterField}":{"$eq":"${filterValue}"}}`
)
const secondEncodedFilterValue = encodeURIComponent(
`{"locale.language":{"$eq":"${localeLanguage}"}}`
)
const thirdEncodedFilterValue = encodeURIComponent(
`{"locale.country":{"$eq":"${localeCountry}"}}`
)
const expectedURL = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?rep=hal&filter=${firstEncodedFilterValue}&filter=${secondEncodedFilterValue}&filter=${thirdEncodedFilterValue}&page=1&pagesize=30&sort=${sort[0].name}&sort=-${sort[1].name}`
expect(actualURL).toBe(expectedURL)
})
it('should throw an unauthorized error when the response is 401', async () => {
fetchMock.mockResponseOnce('', { status: HttpStatus.UNAUTHORIZED })
try {
await remoteApi.fetchByFilter({ filters, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.NOT_AUTHORIZED)
expect(error.statusCode).toBe(HttpStatus.UNAUTHORIZED)
}
})
it('should throw an unknown error when the response is not ok', async () => {
fetchMock.mockResponseOnce('', { status: HttpStatus.BAD_REQUEST })
try {
await remoteApi.fetchByFilter({ filters, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.UNKNOWN_ERROR)
expect(error.statusCode).toBe(HttpStatus.BAD_REQUEST)
}
})
it('should return the response', async () => {
const items = [createDataEntry()]
const caasApiItems = { _embedded: { 'rh:doc': items } }
fetchMock.mockResponseOnce(JSON.stringify(caasApiItems))
const actualRequest = await remoteApi.fetchByFilter({ filters, locale })
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual({
page: 1,
pagesize: 30,
size: undefined,
totalPages: undefined,
items,
})
})
it('should return normalized response if normalized is switched on', async () => {
const items = [createDataEntry()]
const caasApiItems = { _embedded: { 'rh:doc': items } }
fetchMock.mockResponseOnce(JSON.stringify(caasApiItems))
const actualRequest = await remoteApi.fetchByFilter({
filters,
locale,
normalized: true,
})
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual({
page: 1,
pagesize: 30,
size: undefined,
totalPages: undefined,
items,
referenceMap: {},
resolvedReferences: { [items[0]._id]: items[0] },
})
})
it('should return empty array on empty response', async () => {
// CaaS API omits _embedded attribute in response for empty collections or
// queries that don't match any documents.
const emptyResponse = {}
fetchMock.mockResponseOnce(JSON.stringify(emptyResponse))
const actualRequest = await remoteApi.fetchByFilter({ filters, locale })
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual({
page: 1,
pagesize: 30,
size: undefined,
totalPages: undefined,
items: [],
})
})
it('should return empty array on broken response', async () => {
const brokenResponse = { _embedded: {} }
fetchMock.mockResponseOnce(JSON.stringify(brokenResponse))
const actualRequest = await remoteApi.fetchByFilter({ filters, locale })
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual({
page: 1,
pagesize: 30,
size: undefined,
totalPages: undefined,
items: [],
})
})
it('boolean values pass the typecheck', async () => {
const comparisonFilter: QueryBuilderQuery[] = [
{
value: true,
field: filterField,
operator: ComparisonQueryOperatorEnum.EQUALS,
},
]
const arrayFilter: QueryBuilderQuery[] = [
{
value: [true, false, true],
field: filterField,
operator: ArrayQueryOperatorEnum.ALL,
},
]
fetchMock.mockResponseOnce(JSON.stringify(json))
await remoteApi.fetchByFilter({ filters: comparisonFilter, locale })
fetchMock.mockResponseOnce(JSON.stringify(json))
await remoteApi.fetchByFilter({ filters: arrayFilter, locale })
expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('should allow comparison with null values', async () => {
const filter1: QueryBuilderQuery[] = [
{
value: null,
field: filterField,
operator: ComparisonQueryOperatorEnum.EQUALS,
},
]
const filter2: QueryBuilderQuery[] = [
{
value: null,
field: filterField,
operator: ComparisonQueryOperatorEnum.NOT_EQUALS,
},
]
fetchMock.mockResponseOnce(JSON.stringify(json))
await remoteApi.fetchByFilter({ filters: filter1, locale })
fetchMock.mockResponseOnce(JSON.stringify(json))
await remoteApi.fetchByFilter({ filters: filter2, locale })
expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('should return right data if no locale is provided', async () => {
const id = faker.string.uuid()
const id2 = faker.string.uuid()
const localeLanguage = faker.lorem.word(2).toLowerCase()
const localeCountry = faker.lorem.word(2).toUpperCase()
const locale2 = localeLanguage + '_' + localeCountry
const items = [createDataEntry(id, locale), createDataEntry(id2, locale2)]
const caasApiItems = { _embedded: { 'rh:doc': items } }
fetchMock.mockResponseOnce(JSON.stringify(caasApiItems))
const actualRequest = await remoteApi.fetchByFilter({
filters,
})
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual({
page: 1,
pagesize: 30,
size: undefined,
totalPages: undefined,
items,
})
})
it('should return items when fetching remote items', async () => {
const mainMedia = createMediaPicture(
undefined,
config.remotes.remote.locale
)
const referencedMedia = createMediaPicture(
undefined,
config.remotes.remote.locale
)
mainMedia.metaFormData.fsRef = createMediaPictureReference(
referencedMedia._id
)
const firstResponse = { _embedded: { 'rh:doc': [mainMedia] } }
const secondResponse = { _embedded: { 'rh:doc': [referencedMedia] } }
fetchMock
.mockResponseOnce(JSON.stringify(firstResponse))
.mockResponseOnce(JSON.stringify(secondResponse))
const actualRequest = await remoteApi.fetchByFilter({
filters,
locale: 'de_DE',
remoteProject: config.remotes.remote.id,
})
const mappedMainMedia = getMappedMediaPicture(
mainMedia,
config.remotes.remote.locale,
config.remotes.remote.id
)
const mappedReferencedMedia = getMappedMediaPicture(
referencedMedia,
config.remotes.remote.locale,
config.remotes.remote.id
)
mappedMainMedia.meta.fsRef = mappedReferencedMedia
expect(actualRequest).toBeDefined()
expect(actualRequest).toStrictEqual({
page: 1,
pagesize: 30,
size: undefined,
totalPages: undefined,
items: [mappedMainMedia],
})
})
})
describe('fetchNavigation', () => {
let remoteApi: FSXARemoteApi
let config: any
beforeEach(() => {
config = generateRandomConfig()
remoteApi = new FSXARemoteApi(config)
})
it('should trigger the fetch method with locale', () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const initialPath = '/'
remoteApi.fetchNavigation({ initialPath, locale })
const actualURL = fetchMock.mock.calls[0][0]
const expectedURL = `${config.navigationServiceURL}/${config.contentMode}.${config.projectID}?depth=99&format=caas&language=${locale}`
expect(actualURL).toBe(expectedURL)
})
it('should trigger the fetch method with initialPath = /', () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
remoteApi.fetchNavigation({ locale })
const actualURL = fetchMock.mock.calls[0][0]
const expectedURL = `${config.navigationServiceURL}/${config.contentMode}.${config.projectID}?depth=99&format=caas&language=${locale}`
expect(actualURL).toBe(expectedURL)
})
it('should trigger the fetch method with initialPath', () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const initialPath = faker.lorem.words(3).split(' ').join('/')
remoteApi.fetchNavigation({ initialPath, locale })
const actualURL = fetchMock.mock.calls[0][0]
const expectedURL = `${config.navigationServiceURL}/${config.contentMode}.${config.projectID}/by-seo-route/${initialPath}?depth=99&format=caas&all`
expect(actualURL).toBe(expectedURL)
})
it('should throw an not found error when the response is 404', async () => {
fetchMock.mockResponseOnce('', { status: HttpStatus.NOT_FOUND })
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
try {
await remoteApi.fetchNavigation({ locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.NOT_FOUND)
expect(error.statusCode).toBe(HttpStatus.NOT_FOUND)
}
})
it('should throw an unknown error when the response is not ok', async () => {
fetchMock.mockResponseOnce('', { status: HttpStatus.BAD_REQUEST })
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
try {
await remoteApi.fetchNavigation({ locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.UNKNOWN_ERROR)
expect(error.statusCode).toBe(HttpStatus.BAD_REQUEST)
}
})
it('should return the response', async () => {
const expectedResponse = JSON.stringify(faker.helpers.fake("{{lorem.word}}"))
fetchMock.mockResponseOnce(JSON.stringify(expectedResponse))
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const actualResponse = await remoteApi.fetchNavigation({ locale })
expect(actualResponse).toEqual(expectedResponse)
})
it('should throw an unknown error when ? is used in initial path', async () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const initialPath = faker.lorem.words(3).split(' ').join('/') + '?'
try {
await remoteApi.fetchNavigation({ initialPath, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.UNKNOWN_ERROR)
expect(error.statusCode).toBe(HttpStatus.BAD_REQUEST)
}
})
it('should throw an unknown error when # is used in initial path', async () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const locale = `${faker.location.countryCode().toLowerCase()}_${faker.location.countryCode().toLowerCase()}`
const initialPath = faker.lorem.words(3).split(' ').join('/') + '#'
try {
await remoteApi.fetchNavigation({ initialPath, locale })
} catch (error: any) {
expect(error.message).toBe(FSXAApiErrors.UNKNOWN_ERROR)
expect(error.statusCode).toBe(HttpStatus.BAD_REQUEST)
}
})
it('should trigger the fetch method with encoded params when special chars are used in locale or initial path', () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const locale = "*_'();:@&=+$,?%#[]_*'();:@&=+$,?%#[]"
const initialPath = "*_'();:@&=+$,%[]"
remoteApi.fetchNavigation({ initialPath, locale })
const encodedInitialPath = encodeURI(initialPath)
const actualURL = fetchMock.mock.calls[0][0]
const expectedURL = `${config.navigationServiceURL}/${config.contentMode}.${config.projectID}/by-seo-route/${encodedInitialPath}?depth=99&format=caas&all`
expect(actualURL).toBe(expectedURL)
})
})
describe('fetchProjectProperties', () => {
let remoteApi: FSXARemoteApi
let config: any
beforeEach(() => {
config = generateRandomConfig()
remoteApi = new FSXARemoteApi(config)
})
it('should trigger fetchByFilter with correct params', () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const localeLanguage = faker.lorem.word(2).toLowerCase()
const localeCountry = faker.lorem.word(2).toUpperCase()
const locale = localeLanguage + '_' + localeCountry
remoteApi.fetchProjectProperties({ locale })
const actualURL = fetchMock.mock.calls[0][0]
const firstEncodedFilterValue = encodeURIComponent(
`{"fsType":{"$eq":"ProjectProperties"}}`
)
const secondEncodedFilterValue = encodeURIComponent(
`{"locale.language":{"$eq":"${localeLanguage}"}}`
)
const thirdEncodedFilterValue = encodeURIComponent(
`{"locale.country":{"$eq":"${localeCountry}"}}`
)
const expectedURL = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?rep=hal&filter=${firstEncodedFilterValue}&filter=${secondEncodedFilterValue}&filter=${thirdEncodedFilterValue}&page=1&pagesize=30`
expect(actualURL).toBe(expectedURL)
})
it('should trigger fetchByFilter with encoded params when special chars in locale are used', () => {
fetchMock.mockResponseOnce(JSON.stringify(faker.helpers.fake("{{lorem.word}}")))
const localeLanguage = "*'();:@&=+$,?%#[]"
const localeCountry = "*'();:@&=+$,?%#[]"
const locale = localeLanguage + '_' + localeCountry
remoteApi.fetchProjectProperties({ locale })
const actualURL = fetchMock.mock.calls[0][0]
const firstEncodedFilterValue = encodeURIComponent(
`{"fsType":{"$eq":"ProjectProperties"}}`
)
const secondEncodedFilterValue = encodeURIComponent(
`{"locale.language":{"$eq":"${localeLanguage}"}}`
)
const thirdEncodeddFilterValue = encodeURIComponent(
`{"locale.country":{"$eq":"${localeCountry}"}}`
)
const expectedURL = `${config.caasURL}/${config.tenantID}/${config.projectID}.${config.contentMode}.content?rep=hal&filter=${firstEncodedFilterValue}&filter=${secondEncodedFilterValue}&filter=${thirdEncodeddFilterValue}&page=1&pagesize=30`
expect(actualURL).toBe(expectedURL)
})
})
describe('additionalHooks', () => {
const firstId = faker.string.uuid()
const firstlabel = faker.string.alpha()
const firstSeoRoute = `/${firstlabel}/`
const secondId = faker.string.uuid()
const secondlabel = faker.string.alpha()
const secondSeoRoute = `/${secondlabel}/`
const thirdId = faker.string.uuid()
const thirdlabel = faker.string.alpha()
const thirdSeoRoute = `/${thirdlabel}/`
const responseJSON = {
idMap: {
[firstId]: {
id: firstId,
label: firstlabel,