-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathportal.test.js
More file actions
3789 lines (3315 loc) · 150 KB
/
Copy pathportal.test.js
File metadata and controls
3789 lines (3315 loc) · 150 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
/**
* Unit tests for pure/near-pure functions in portal.js.
*
* portal.js is a browser script (no module exports), so we load it via
* vm.runInThisContext into the jsdom global scope that Jest provides.
*
* @jest-environment jsdom
*/
const fs = require('fs');
const path = require('path');
// Load jsonpath-plus. The UMD bundle detects CommonJS `exports` and writes
// there instead of globalThis, so we capture and re-export as a global.
const _jpExports = {};
const _jpModule = { exports: _jpExports };
(new Function('exports', 'module', fs.readFileSync(
path.resolve(__dirname, '../portal_generator/assets/jsonpath-plus.min.js'),
'utf-8',
)))(_jpExports, _jpModule);
globalThis.JSONPath = _jpExports.JSONPath ? _jpExports : _jpModule.exports;
// Load portal.js into the module scope so all functions are available.
// eval in module scope makes function declarations accessible as local vars.
const portalJs = fs.readFileSync(
path.resolve(__dirname, '../portal_generator/assets/portal.js'),
'utf-8',
);
// Stub DOMContentLoaded to prevent side-effects during load.
const _origAddEventListener = document.addEventListener;
document.addEventListener = function (event, fn) {
if (event === 'DOMContentLoaded') return;
return _origAddEventListener.call(this, event, fn);
};
eval(portalJs);
document.addEventListener = _origAddEventListener;
// ---------------------------------------------------------------------------
// Helper: set up DOM elements so getSelectedRegion() returns the desired value.
// ---------------------------------------------------------------------------
function makeSelect(id, value) {
const sel = document.createElement('select');
sel.id = id;
const opt = document.createElement('option');
opt.value = value;
sel.appendChild(opt);
sel.value = value;
document.body.appendChild(sel);
return sel;
}
function cleanupServerElements() {
['serverSelect', 'regionPreset', 'regionCustomInput'].forEach((id) => {
const el = document.getElementById(id);
if (el) el.remove();
});
}
function withServerType(type, region, fn) {
cleanupServerElements();
makeSelect('serverSelect', type);
if ((type === 'platform' || type === 'eu') && region) {
makeSelect('regionPreset', region);
}
try {
fn();
} finally {
cleanupServerElements();
}
}
function withRegion(region, fn) {
if (region) {
withServerType('platform', region, fn);
} else {
cleanupServerElements();
try {
fn();
} finally {
cleanupServerElements();
}
}
}
function withSessionStorage(storedType, storedRegion, fn) {
var prevType = sessionStorage.getItem('anypoint_server_type');
var prevRegion = sessionStorage.getItem('anypoint_region');
if (storedType === null) sessionStorage.removeItem('anypoint_server_type');
else sessionStorage.setItem('anypoint_server_type', storedType);
if (storedRegion === null) sessionStorage.removeItem('anypoint_region');
else sessionStorage.setItem('anypoint_region', storedRegion);
try {
fn();
} finally {
if (prevType === null) sessionStorage.removeItem('anypoint_server_type');
else sessionStorage.setItem('anypoint_server_type', prevType);
if (prevRegion === null) sessionStorage.removeItem('anypoint_region');
else sessionStorage.setItem('anypoint_region', prevRegion);
}
}
// ===========================================================================
// getSelectedServerType
// ===========================================================================
describe('getSelectedServerType', () => {
test('returns us when no select element exists', () => {
expect(getSelectedServerType()).toBe('us');
});
test('returns us when select is set to us', () => {
withServerType('us', null, () => {
expect(getSelectedServerType()).toBe('us');
});
});
test('returns eu when select is set to eu', () => {
withServerType('eu', null, () => {
expect(getSelectedServerType()).toBe('eu');
});
});
test('returns platform when select is set to platform', () => {
withServerType('platform', 'ca1', () => {
expect(getSelectedServerType()).toBe('platform');
});
});
// --- W-22945464: sessionStorage fallback when DOM is at default ---
test('returns sessionStorage value when DOM is at default us and storage has eu (bug repro)', () => {
withServerType('us', null, () => {
withSessionStorage('eu', 'eu1', () => {
expect(getSelectedServerType()).toBe('eu');
});
});
});
test('returns sessionStorage value when DOM element is missing and storage has platform', () => {
cleanupServerElements();
withSessionStorage('platform', 'ca1', () => {
expect(getSelectedServerType()).toBe('platform');
});
});
test('prefers DOM value when DOM is non-default, even if storage says otherwise', () => {
withServerType('platform', 'ca1', () => {
withSessionStorage('eu', 'eu1', () => {
expect(getSelectedServerType()).toBe('platform');
});
});
});
test('returns us when both DOM and sessionStorage are empty', () => {
cleanupServerElements();
withSessionStorage(null, null, () => {
expect(getSelectedServerType()).toBe('us');
});
});
});
// ===========================================================================
// getSelectedRegion
// ===========================================================================
describe('getSelectedRegion', () => {
test('returns null when server type is us', () => {
withServerType('us', null, () => {
expect(getSelectedRegion()).toBeNull();
});
});
test('returns null when server type is us even with sessionStorage region', () => {
withServerType('us', null, () => {
withSessionStorage('us', 'eu1', () => {
expect(getSelectedRegion()).toBeNull();
});
});
});
test('returns region from DOM when regionPreset is set', () => {
withServerType('eu', 'eu2', () => {
expect(getSelectedRegion()).toBe('eu2');
});
});
test('returns region from DOM when platform regionPreset is set', () => {
withServerType('platform', 'ca1', () => {
expect(getSelectedRegion()).toBe('ca1');
});
});
// --- W-22945464: sessionStorage fallback when DOM regionPreset is missing ---
test('returns sessionStorage region when DOM has eu but no regionPreset (bug repro)', () => {
cleanupServerElements();
makeSelect('serverSelect', 'eu');
withSessionStorage('eu', 'eu1', () => {
expect(getSelectedRegion()).toBe('eu1');
});
cleanupServerElements();
});
test('returns sessionStorage region when DOM has platform but no regionPreset for ca1', () => {
cleanupServerElements();
makeSelect('serverSelect', 'platform');
withSessionStorage('platform', 'ca1', () => {
expect(getSelectedRegion()).toBe('ca1');
});
cleanupServerElements();
});
test('returns sessionStorage region when DOM has platform but no regionPreset for jp1', () => {
cleanupServerElements();
makeSelect('serverSelect', 'platform');
withSessionStorage('platform', 'jp1', () => {
expect(getSelectedRegion()).toBe('jp1');
});
cleanupServerElements();
});
test('prefers DOM region over sessionStorage when both are set', () => {
withServerType('eu', 'eu2', () => {
withSessionStorage('eu', 'eu1', () => {
expect(getSelectedRegion()).toBe('eu2');
});
});
});
test('returns null when neither DOM nor sessionStorage has a region', () => {
cleanupServerElements();
makeSelect('serverSelect', 'eu');
withSessionStorage(null, null, () => {
expect(getSelectedRegion()).toBeNull();
});
cleanupServerElements();
});
test('returns custom region from DOM when regionPreset is custom', () => {
cleanupServerElements();
makeSelect('serverSelect', 'platform');
const regionPreset = makeSelect('regionPreset', 'custom');
const customInput = document.createElement('input');
customInput.id = 'regionCustomInput';
customInput.value = 'custom-region-1';
document.body.appendChild(customInput);
expect(getSelectedRegion()).toBe('custom-region-1');
customInput.remove();
cleanupServerElements();
});
test('returns null when regionPreset is custom but customInput is empty', () => {
cleanupServerElements();
makeSelect('serverSelect', 'platform');
const regionPreset = makeSelect('regionPreset', 'custom');
const customInput = document.createElement('input');
customInput.id = 'regionCustomInput';
customInput.value = '';
document.body.appendChild(customInput);
expect(getSelectedRegion()).toBeNull();
customInput.remove();
cleanupServerElements();
});
test('returns null when serverSelect is missing', () => {
cleanupServerElements();
expect(getSelectedRegion()).toBeNull();
});
});
// ===========================================================================
// getSelectedBaseUrl
// ===========================================================================
describe('getSelectedBaseUrl', () => {
test('returns US base URL by default', () => {
expect(getSelectedBaseUrl()).toBe('https://anypoint.mulesoft.com');
});
test('returns EU base URL with eu1 default when EU selected', () => {
withServerType('eu', null, () => {
expect(getSelectedBaseUrl()).toBe('https://eu1.anypoint.mulesoft.com');
});
});
test('returns EU base URL with custom region when EU selected with region', () => {
withServerType('eu', 'eu2', () => {
expect(getSelectedBaseUrl()).toBe('https://eu2.anypoint.mulesoft.com');
});
});
test('returns platform base URL with region when platform selected', () => {
withServerType('platform', 'ca1', () => {
expect(getSelectedBaseUrl()).toBe('https://ca1.platform.mulesoft.com');
});
});
test('returns platform base URL with ca1 default when no region preset', () => {
withServerType('platform', null, () => {
expect(getSelectedBaseUrl()).toBe('https://ca1.platform.mulesoft.com');
});
});
});
// ===========================================================================
// getNonRegionVars
// ===========================================================================
describe('getNonRegionVars', () => {
test('returns empty object for null server', () => {
expect(getNonRegionVars(null)).toEqual({});
});
test('returns empty object when server has no variables', () => {
expect(getNonRegionVars({ url: 'https://x.com' })).toEqual({});
});
test('filters out region and REGION_ID', () => {
const server = {
variables: {
region: { default: 'us-east-1' },
REGION_ID: { default: 'eu1' },
version: { default: 'v1' },
},
};
expect(getNonRegionVars(server)).toEqual({
version: { default: 'v1' },
});
});
test('returns all variables when none are region-related', () => {
const server = {
variables: {
version: { default: 'v2' },
env: { default: 'prod' },
},
};
expect(getNonRegionVars(server)).toEqual({
version: { default: 'v2' },
env: { default: 'prod' },
});
});
});
// ===========================================================================
// pickServerTemplate
// ===========================================================================
describe('pickServerTemplate', () => {
const usServer = { url: 'https://anypoint.mulesoft.com/api/v1' };
const euServer = {
url: 'https://{region}.anypoint.mulesoft.com/api/v1',
variables: { region: { default: 'eu1' } },
};
const euServerLegacy = { url: 'https://eu1.anypoint.mulesoft.com/api/v1' };
const platformServer = {
url: 'https://{region}.platform.mulesoft.com/api/v1',
variables: { region: { default: 'ca1' } },
};
test('returns null for empty/null array', () => {
expect(pickServerTemplate(null)).toBeNull();
expect(pickServerTemplate([])).toBeNull();
});
test('returns first server (US) when no region selected', () => {
withServerType('us', null, () => {
expect(pickServerTemplate([usServer, euServer, platformServer])).toBe(usServer);
});
});
test('returns parameterized EU server when EU is selected', () => {
withServerType('eu', null, () => {
expect(pickServerTemplate([usServer, euServer, platformServer])).toBe(euServer);
});
});
test('falls back to legacy EU server when no parameterized EU exists', () => {
withServerType('eu', null, () => {
expect(pickServerTemplate([usServer, euServerLegacy, platformServer])).toBe(euServerLegacy);
});
});
test('returns platform server when platform is selected', () => {
withServerType('platform', 'ca1', () => {
expect(pickServerTemplate([usServer, euServer, platformServer])).toBe(platformServer);
});
});
test('falls back to first server when EU selected but no EU server exists', () => {
withServerType('eu', null, () => {
expect(pickServerTemplate([usServer, platformServer])).toBe(usServer);
});
});
test('falls back to first server when platform selected but no platform server exists', () => {
withServerType('platform', 'ca1', () => {
expect(pickServerTemplate([usServer, euServer])).toBe(usServer);
});
});
});
// ===========================================================================
// resolveServerUrl
// ===========================================================================
describe('resolveServerUrl', () => {
test('returns default URL for null server', () => {
expect(resolveServerUrl(null, null)).toBe('https://anypoint.mulesoft.com');
});
test('returns URL as-is when no variables', () => {
const server = { url: 'https://anypoint.mulesoft.com/api/v1' };
expect(resolveServerUrl(server, null)).toBe('https://anypoint.mulesoft.com/api/v1');
});
test('substitutes region variable when platform region selected', () => {
const server = {
url: 'https://{region}.platform.mulesoft.com/api/v1',
variables: { region: { default: 'ca1' } },
};
withRegion('sg1', () => {
expect(resolveServerUrl(server, null)).toBe(
'https://sg1.platform.mulesoft.com/api/v1',
);
});
});
test('substitutes region variable when EU region selected', () => {
const server = {
url: 'https://{region}.anypoint.mulesoft.com/api/v1',
variables: { region: { default: 'eu1' } },
};
withServerType('eu', 'eu2', () => {
expect(resolveServerUrl(server, null)).toBe(
'https://eu2.anypoint.mulesoft.com/api/v1',
);
});
});
test('uses variable default when region is not selected', () => {
const server = {
url: 'https://{region}.platform.mulesoft.com/api/v1',
variables: { region: { default: 'ca1' } },
};
withRegion(null, () => {
expect(resolveServerUrl(server, null)).toBe(
'https://ca1.platform.mulesoft.com/api/v1',
);
});
});
test('substitutes non-region variable using default (no opId)', () => {
const server = {
url: 'https://api.com/{version}/resources',
variables: { version: { default: 'v2' } },
};
withRegion(null, () => {
expect(resolveServerUrl(server, null)).toBe(
'https://api.com/v2/resources',
);
});
});
test('substitutes multiple variables', () => {
const server = {
url: 'https://{region}.platform.mulesoft.com/{version}',
variables: {
region: { default: 'ca1' },
version: { default: 'v1' },
},
};
withRegion('sg1', () => {
expect(resolveServerUrl(server, null)).toBe(
'https://sg1.platform.mulesoft.com/v1',
);
});
});
test('skips variable when placeholder not in URL', () => {
const server = {
url: 'https://api.com/v1',
variables: { region: { default: 'us' } },
};
withRegion('eu', () => {
expect(resolveServerUrl(server, null)).toBe('https://api.com/v1');
});
});
});
// ===========================================================================
// Region × domain matrix (W-22861359)
// ===========================================================================
describe('isServerValidForRegion', () => {
const anypointGlobal = { url: 'https://anypoint.mulesoft.com/api' };
const anypointRegional = {
url: 'https://{region}.anypoint.mulesoft.com/api',
variables: { region: { default: 'eu1' } },
};
const platformRegional = {
url: 'https://{region}.platform.mulesoft.com/api',
variables: { region: { default: 'ca1' } },
};
const anypointLegacyEu = { url: 'https://eu1.anypoint.mulesoft.com/api' };
test('us global: only anypoint global is valid (region=null)', () => {
expect(isServerValidForRegion(anypointGlobal, null)).toBe(true);
expect(isServerValidForRegion(anypointRegional, null)).toBe(true);
expect(isServerValidForRegion(platformRegional, null)).toBe(true);
});
test('eu1: only anypoint regional, NOT platform', () => {
expect(isServerValidForRegion(anypointGlobal, 'eu1')).toBe(false);
expect(isServerValidForRegion(anypointRegional, 'eu1')).toBe(true);
expect(isServerValidForRegion(platformRegional, 'eu1')).toBe(false);
});
test('ca1: only platform, NOT anypoint regional', () => {
expect(isServerValidForRegion(anypointGlobal, 'ca1')).toBe(false);
expect(isServerValidForRegion(anypointRegional, 'ca1')).toBe(false);
expect(isServerValidForRegion(platformRegional, 'ca1')).toBe(true);
});
test('jp1: only platform, NOT anypoint regional', () => {
expect(isServerValidForRegion(anypointGlobal, 'jp1')).toBe(false);
expect(isServerValidForRegion(anypointRegional, 'jp1')).toBe(false);
expect(isServerValidForRegion(platformRegional, 'jp1')).toBe(true);
});
test('in1: only platform, NOT anypoint regional', () => {
expect(isServerValidForRegion(anypointGlobal, 'in1')).toBe(false);
expect(isServerValidForRegion(anypointRegional, 'in1')).toBe(false);
expect(isServerValidForRegion(platformRegional, 'in1')).toBe(true);
});
test('au1: only platform, NOT anypoint regional', () => {
expect(isServerValidForRegion(anypointGlobal, 'au1')).toBe(false);
expect(isServerValidForRegion(anypointRegional, 'au1')).toBe(false);
expect(isServerValidForRegion(platformRegional, 'au1')).toBe(true);
});
test('legacy hardcoded eu1 server is valid for eu1', () => {
expect(isServerValidForRegion(anypointLegacyEu, 'eu1')).toBe(true);
expect(isServerValidForRegion(anypointLegacyEu, 'ca1')).toBe(false);
});
test('unknown region does not filter (returns true to avoid hiding valid endpoints)', () => {
expect(isServerValidForRegion(anypointGlobal, 'sg1')).toBe(true);
expect(isServerValidForRegion(anypointRegional, 'sg1')).toBe(true);
expect(isServerValidForRegion(platformRegional, 'sg1')).toBe(true);
});
test('null/undefined server returns false', () => {
expect(isServerValidForRegion(null, 'eu1')).toBe(false);
expect(isServerValidForRegion(undefined, 'eu1')).toBe(false);
});
});
describe('filterServersForRegion', () => {
const anypointGlobal = { url: 'https://anypoint.mulesoft.com/api' };
const anypointRegional = {
url: 'https://{region}.anypoint.mulesoft.com/api',
variables: { region: { default: 'eu1' } },
};
const platformRegional = {
url: 'https://{region}.platform.mulesoft.com/api',
variables: { region: { default: 'ca1' } },
};
const all = [anypointGlobal, anypointRegional, platformRegional];
test('eu1 keeps only anypoint regional', () => {
expect(filterServersForRegion(all, 'eu1')).toEqual([anypointRegional]);
});
test('ca1 keeps only platform regional', () => {
expect(filterServersForRegion(all, 'ca1')).toEqual([platformRegional]);
});
test('jp1 keeps only platform regional', () => {
expect(filterServersForRegion(all, 'jp1')).toEqual([platformRegional]);
});
test('in1 keeps only platform regional', () => {
expect(filterServersForRegion(all, 'in1')).toEqual([platformRegional]);
});
test('au1 keeps only platform regional', () => {
expect(filterServersForRegion(all, 'au1')).toEqual([platformRegional]);
});
test('null region (us) returns all', () => {
expect(filterServersForRegion(all, null)).toEqual(all);
});
test('unknown region returns all (no filter)', () => {
expect(filterServersForRegion(all, 'sg1')).toEqual(all);
});
test('empty/null input returns []', () => {
expect(filterServersForRegion(null, 'eu1')).toEqual([]);
expect(filterServersForRegion([], 'eu1')).toEqual([]);
});
});
// ===========================================================================
// buildUrlBarHtml
// ===========================================================================
describe('buildUrlBarHtml', () => {
test('renders method, server, and path', () => {
const html = buildUrlBarHtml('GET', 'https://api.com', '/resources');
expect(html).toContain('method-get');
expect(html).toContain('GET');
expect(html).toContain('https://api.com');
expect(html).toContain('/resources');
});
test('includes link when provided', () => {
const html = buildUrlBarHtml('POST', 'https://api.com', '/items', 'detail.html#op-create');
expect(html).toContain('<a href="detail.html#op-create"');
expect(html).toContain('</a>');
});
test('omits link when not provided', () => {
const html = buildUrlBarHtml('DELETE', 'https://api.com', '/items/1');
expect(html).not.toContain('<a ');
});
test('escapes HTML in parameters', () => {
const html = buildUrlBarHtml('GET', 'https://api.com', '/search?q=<script>');
expect(html).not.toContain('<script>');
expect(html).toContain('<script>');
});
});
// ===========================================================================
// extractXOriginValues
// ===========================================================================
describe('extractXOriginValues', () => {
// --- No fieldPath: returns responseBody wrapped as array ---
test('returns array responseBody as-is when no fieldPath', () => {
const data = ['a', 'b', 'c'];
expect(extractXOriginValues(data, null)).toEqual(['a', 'b', 'c']);
});
test('wraps non-array responseBody when no fieldPath', () => {
expect(extractXOriginValues('single', null)).toEqual(['single']);
expect(extractXOriginValues(42, null)).toEqual([42]);
});
test('wraps object responseBody when no fieldPath', () => {
const obj = { id: 1 };
expect(extractXOriginValues(obj, null)).toEqual([{ id: 1 }]);
});
test('returns array with falsy value when responseBody is falsy and no fieldPath', () => {
// !responseBody is true → if Array.isArray check fails → [responseBody]
expect(extractXOriginValues(null, null)).toEqual([null]);
expect(extractXOriginValues(undefined, null)).toEqual([undefined]);
expect(extractXOriginValues('', '')).toEqual(['']);
});
// --- With fieldPath: delegates to extractByPath via JSONPath ---
test('extracts array from nested path', () => {
const data = { data: { items: ['x', 'y', 'z'] } };
expect(extractXOriginValues(data, '$.data.items[*]')).toEqual(['x', 'y', 'z']);
});
test('extracts single value and wraps in array', () => {
const data = { name: 'test-env' };
expect(extractXOriginValues(data, '$.name')).toEqual(['test-env']);
});
test('returns empty array when path does not match', () => {
const data = { name: 'test' };
expect(extractXOriginValues(data, '$.nonexistent')).toEqual([]);
});
test('extracts values from array of objects', () => {
const data = {
environments: [
{ id: 'env-1', name: 'Production' },
{ id: 'env-2', name: 'Sandbox' },
],
};
expect(extractXOriginValues(data, '$.environments[*].id')).toEqual(['env-1', 'env-2']);
});
test('handles path without $ prefix', () => {
const data = { items: [1, 2, 3] };
// extractByPath prepends $. if path doesn't start with $
expect(extractXOriginValues(data, 'items[*]')).toEqual([1, 2, 3]);
});
test('extracts nested field from single object', () => {
const data = { org: { id: 'abc-123' } };
expect(extractXOriginValues(data, '$.org.id')).toEqual(['abc-123']);
});
});
// ===========================================================================
// setNestedValue
// ===========================================================================
describe('setNestedValue', () => {
test('sets simple key', () => {
const obj = {};
setNestedValue(obj, 'name', 'test');
expect(obj).toEqual({ name: 'test' });
});
test('sets dot-path key', () => {
const obj = {};
setNestedValue(obj, 'endpoint.uri', '"http://x"');
expect(obj).toEqual({ endpoint: { uri: 'http://x' } });
});
test('sets array index', () => {
const obj = {};
setNestedValue(obj, 'items[0]', '"a"');
expect(obj).toEqual({ items: ['a'] });
});
test('sets deep mixed path', () => {
const obj = {};
setNestedValue(obj, 'data.list[0].name', '"x"');
expect(obj).toEqual({ data: { list: [{ name: 'x' }] } });
});
test('preserves existing keys', () => {
const obj = { endpoint: { type: 'http' } };
setNestedValue(obj, 'endpoint.uri', '"http://x"');
expect(obj).toEqual({ endpoint: { type: 'http', uri: 'http://x' } });
});
test('handles numeric string as value', () => {
const obj = {};
setNestedValue(obj, 'port', '8080');
expect(obj).toEqual({ port: 8080 });
});
});
// ===========================================================================
// tryParseJson
// ===========================================================================
describe('tryParseJson', () => {
test('parses valid JSON number', () => {
expect(tryParseJson('42')).toBe(42);
});
test('parses valid JSON object', () => {
expect(tryParseJson('{"a":1}')).toEqual({ a: 1 });
});
test('returns original string for invalid JSON', () => {
expect(tryParseJson('hello')).toBe('hello');
});
test('parses boolean strings', () => {
expect(tryParseJson('true')).toBe(true);
expect(tryParseJson('false')).toBe(false);
});
test('parses null', () => {
expect(tryParseJson('null')).toBeNull();
});
});
// ===========================================================================
// syncBodyFieldsToRaw
// ===========================================================================
describe('syncBodyFieldsToRaw', () => {
afterEach(() => {
document.body.innerHTML = '';
window.aceEditors = {};
});
function buildPanel(sid, fields) {
const panel = document.createElement('div');
panel.id = 'wf-try-' + sid;
const editorDiv = document.createElement('div');
editorDiv.id = 'wf-body-' + sid;
editorDiv.className = 'wf-request-editor-cm';
panel.appendChild(editorDiv);
// Mock Ace editor
let mockContent = '';
const mockEditor = {
getValue() {
return mockContent;
},
setValue(content) {
mockContent = content;
}
};
window.aceEditors = window.aceEditors || {};
window.aceEditors['wf-body-' + sid] = mockEditor;
fields.forEach(({ name, value }) => {
const input = document.createElement('input');
input.setAttribute('data-in', 'body');
input.setAttribute('data-wf-param', name);
input.value = value;
panel.appendChild(input);
});
document.body.appendChild(panel);
return mockEditor;
}
test('populates Ace editor with JSON from inputs', () => {
const editor = buildPanel('test-0', [
{ name: 'name', value: 'my-api' },
{ name: 'active', value: 'true' },
]);
syncBodyFieldsToRaw('test-0');
const result = JSON.parse(editor.getValue());
expect(result).toEqual({ name: 'my-api', active: true });
});
test('builds nested JSON from dot-path fields', () => {
const editor = buildPanel('test-1', [
{ name: 'endpoint.uri', value: 'http://backend.example.com' },
{ name: 'endpoint.type', value: 'http' },
]);
syncBodyFieldsToRaw('test-1');
const result = JSON.parse(editor.getValue());
expect(result).toEqual({
endpoint: { uri: 'http://backend.example.com', type: 'http' },
});
});
test('produces empty editor when all inputs are empty', () => {
const editor = buildPanel('test-2', [
{ name: 'name', value: '' },
]);
syncBodyFieldsToRaw('test-2');
expect(editor.getValue()).toBe('');
});
test('does nothing when panel does not exist', () => {
// Should not throw
syncBodyFieldsToRaw('nonexistent');
});
});
// ===========================================================================
// renderOutputDropdownRow
// ===========================================================================
describe('renderOutputDropdownRow', () => {
test('renders a table row with the output name in the first cell', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'groupId', ['g1', 'g2']);
expect(html).toContain('<tr>');
expect(html).toContain('<code>groupId</code>');
});
test('renders a select element with wf-output-select class', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'groupId', ['g1', 'g2']);
expect(html).toContain('class="wf-output-select"');
expect(html).toContain('<select');
expect(html).toContain('</select>');
});
test('first option is pre-selected', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'id', ['env-1', 'env-2', 'env-3']);
expect(html).toContain('value="0" selected');
// Only the first option should be selected
expect(html.match(/ selected/g).length).toBe(1);
});
test('renders one option per value', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'name', ['a', 'b', 'c']);
expect(html).toContain('value="0"');
expect(html).toContain('value="1"');
expect(html).toContain('value="2"');
expect(html.match(/<option/g).length).toBe(3);
});
test('options always include array index prefix', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'id', ['alpha', 'beta', 'gamma']);
expect(html).toContain('[0]');
expect(html).toContain('[1]');
expect(html).toContain('[2]');
});
test('without labels shows [i] value format', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'id', ['abc-123', 'def-456']);
expect(html).toContain('[0] abc-123');
expect(html).toContain('[1] def-456');
});
test('with labels shows [i] label (value) format when label differs from value', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'envId',
['f3b2a1c0', 'a9c8e2f1'],
['Production', 'Sandbox'],
);
expect(html).toContain('[0] Production (f3b2a1c0)');
expect(html).toContain('[1] Sandbox (a9c8e2f1)');
});
test('with labels shows [i] value format when label equals value', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'name',
['foo', 'bar'],
['foo', 'bar'],
);
expect(html).toContain('[0] foo');
expect(html).toContain('[1] bar');
// Should NOT add redundant parenthetical
expect(html).not.toContain('(foo)');
expect(html).not.toContain('(bar)');
});
test('without labels truncates long values at 80 chars', () => {
const longVal = 'x'.repeat(100);
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'val', [longVal]);
// [0] + space prefix + 80 chars of value
expect(html).toContain('x'.repeat(80));
expect(html).not.toContain('x'.repeat(81));
});
test('with labels truncates long value at 60 chars in parenthetical', () => {
const longVal = 'x'.repeat(100);
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'val', [longVal], ['My Label']);
expect(html).toContain('x'.repeat(60));
expect(html).not.toContain('x'.repeat(61));
});
test('null labels argument falls back to value-only format', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'id', ['abc', 'def'], null);
expect(html).toContain('[0] abc');
expect(html).toContain('[1] def');
expect(html).not.toContain('(abc)');
});
test('select carries data-skill, data-step, and data-output-name attributes', () => {
const html = renderOutputDropdownRow('my-skill-0', 'my-skill', 0, 'assetId', ['a']);
expect(html).toContain('data-skill="my-skill"');
expect(html).toContain('data-step="0"');
expect(html).toContain('data-output-name="assetId"');
});
test('does not contain radio buttons or row-selection markup', () => {
const html = renderOutputDropdownRow('skill-0', 'skill', 0, 'id', ['a', 'b']);
expect(html).not.toContain('type="radio"');
expect(html).not.toContain('wf-row-selected');
expect(html).not.toContain('data-row-index');
});
});
// ===========================================================================
// Skill Actions Dropdown
// ===========================================================================
describe('toggleSkillDropdown', () => {
afterEach(() => {
document.body.innerHTML = '';
});
function buildSplitBtn(slug) {
const wrapper = document.createElement('div');
wrapper.className = 'skill-split-btn';
wrapper.id = 'skill-actions-' + slug;
const main = document.createElement('button');
main.className = 'skill-split-main';
wrapper.appendChild(main);
const toggle = document.createElement('button');
toggle.className = 'skill-split-toggle';
toggle.setAttribute('aria-expanded', 'false');
wrapper.appendChild(toggle);
const menu = document.createElement('div');
menu.className = 'skill-dropdown-menu';
menu.id = 'skill-dropdown-menu-' + slug;
menu.style.display = 'none';
wrapper.appendChild(menu);
document.body.appendChild(wrapper);
return { wrapper, main, toggle, menu };
}
test('opens a closed dropdown', () => {
const { toggle, menu } = buildSplitBtn('test-skill');
toggleSkillDropdown('test-skill');
expect(menu.style.display).toBe('block');
expect(toggle.getAttribute('aria-expanded')).toBe('true');
});
test('closes an open dropdown', () => {
const { toggle, menu } = buildSplitBtn('test-skill');
menu.style.display = 'block';
toggle.setAttribute('aria-expanded', 'true');
toggleSkillDropdown('test-skill');
expect(menu.style.display).toBe('none');
expect(toggle.getAttribute('aria-expanded')).toBe('false');
});
test('closes other open dropdowns when opening a new one', () => {
const first = buildSplitBtn('skill-a');
const second = buildSplitBtn('skill-b');
first.menu.style.display = 'block';
first.toggle.setAttribute('aria-expanded', 'true');
toggleSkillDropdown('skill-b');
expect(first.menu.style.display).toBe('none');