-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathstdcm-page-model.ts
813 lines (678 loc) · 30 KB
/
stdcm-page-model.ts
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
import fs from 'fs';
import path from 'path';
import { expect, type Locator, type Page } from '@playwright/test';
import {
CI_SUGGESTIONS,
DEFAULT_DETAILS,
DESTINATION_DETAILS,
LIGHT_DESTINATION_DETAILS,
LIGHT_ORIGIN_DETAILS,
ORIGIN_DETAILS,
VIA_STOP_TIMES,
VIA_STOP_TYPES,
} from '../assets/stdcm-const';
import { EXPLICIT_UI_STABILITY_TIMEOUT, STDCM_SIMULATION_TIMEOUT } from '../assets/timeout-const';
import { logger } from '../logging-fixture';
import { getTranslations, handleAndVerifyInput } from '../utils';
import HomePage from './home-page-model';
import readJsonFile from '../utils/file-utils';
import type { ConsistFields } from '../utils/types';
type StdcmTranslations = {
stdcmErrors: {
noScheduledPoint: string;
};
trainPath: {
warningMinStopTime: string;
};
simulation: {
results: {
simulationName: {
withoutOutputs: string;
};
};
};
};
const enTranslations: StdcmTranslations = readJsonFile('public/locales/en/stdcm.json');
const frTranslations: StdcmTranslations = readJsonFile('public/locales/fr/stdcm.json');
interface TableRow {
index: number;
operationalPoint: string;
code: string;
endStop: string | null;
passageStop: string | null;
startStop: string | null;
weight: string | null;
refEngine: string | null;
}
class STDCMPage extends HomePage {
readonly debugButton: Locator;
readonly notificationHeader: Locator;
readonly consistCard: Locator;
readonly originCard: Locator;
readonly destinationCard: Locator;
readonly mapContainer: Locator;
readonly tractionEngineField: Locator;
readonly towedRollingStockField: Locator;
readonly tonnageField: Locator;
readonly lengthField: Locator;
readonly speedLimitTagField: Locator;
readonly maxSpeedField: Locator;
readonly addViaButton: Locator;
readonly anteriorLinkedTrainContainer: Locator;
readonly anteriorAddLinkedPathButton: Locator;
readonly posteriorLinkedTrainContainer: Locator;
readonly posteriorAddLinkedPathButton: Locator;
readonly launchSimulationButton: Locator;
readonly originChField: Locator;
readonly destinationChField: Locator;
readonly originCiField: Locator;
readonly destinationCiField: Locator;
readonly viaIcon: Locator;
readonly viaDeleteButton: Locator;
readonly originArrival: Locator;
readonly dateOriginArrival: Locator;
readonly timeOriginArrival: Locator;
readonly toleranceOriginArrival: Locator;
readonly destinationArrival: Locator;
readonly dateDestinationArrival: Locator;
readonly timeDestinationArrival: Locator;
readonly closeTimePickerButton: Locator;
readonly toleranceDestinationArrival: Locator;
readonly closeTolerancePickerButton: Locator;
readonly warningBox: Locator;
readonly suggestionList: Locator;
readonly suggestionNS: Locator;
readonly suggestionNWS: Locator;
readonly suggestionSS: Locator;
readonly suggestionMES: Locator;
readonly suggestionMWS: Locator;
readonly dynamicOriginCh: Locator;
readonly dynamicDestinationCh: Locator;
readonly dynamicOriginCi: Locator;
readonly dynamicDestinationCi: Locator;
readonly suggestionItems: Locator;
readonly simulationStatus: Locator;
readonly simulationList: Locator;
readonly incrementButton: Locator;
readonly allViasButton: Locator;
readonly retainSimulationButton: Locator;
readonly downloadSimulationButton: Locator;
readonly downloadLink: Locator;
readonly startNewQueryButton: Locator;
readonly startNewQueryWithDataButton: Locator;
readonly originMarker: Locator;
readonly destinationMarker: Locator;
readonly viaMarker: Locator;
readonly mapResultContainer: Locator;
readonly originResultMarker: Locator;
readonly destinationResultMarker: Locator;
readonly viaResultMarker: Locator;
readonly simulationResultTable: Locator;
readonly simulationLengthAndDuration: Locator;
readonly helpButton: Locator;
constructor(page: Page) {
super(page);
this.notificationHeader = page.locator('#notification');
this.debugButton = page.getByTestId('stdcm-debug-button');
this.helpButton = page.getByTestId('stdcm-help-button');
this.mapContainer = page.locator('#stdcm-map-config');
this.consistCard = page.locator('.stdcm-consist-container .stdcm-card');
this.originCard = page.locator('.stdcm-card:has(.stdcm-origin-icon)');
this.destinationCard = page.locator('.stdcm-card:has(.stdcm-destination-icon)');
this.tractionEngineField = page.locator('#tractionEngine');
this.towedRollingStockField = page.locator('#towedRollingStock');
this.tonnageField = page.locator('#tonnage');
this.lengthField = page.locator('#length');
this.speedLimitTagField = page.locator('#speed-limit-by-tag-selector');
this.maxSpeedField = page.locator('#maxSpeed');
this.addViaButton = page.locator('.stdcm-vias-list button .stdcm-card__body.add-via');
this.anteriorLinkedTrainContainer = page.locator(
'.stdcm-linked-train-search-container.anterior-linked-train'
);
this.anteriorAddLinkedPathButton =
this.anteriorLinkedTrainContainer.locator('.add-linked-train');
this.posteriorLinkedTrainContainer = page.locator(
'.stdcm-linked-train-search-container.posterior-linked-train'
);
this.posteriorAddLinkedPathButton =
this.posteriorLinkedTrainContainer.locator('.add-linked-train');
this.launchSimulationButton = page.getByTestId('launch-simulation-button');
this.originChField = this.originCard.locator('[data-testid="operational-point-ch"]');
this.destinationChField = this.destinationCard.locator('[data-testid="operational-point-ch"]');
this.originCiField = this.originCard.locator('[data-testid="operational-point-ci"]');
this.destinationCiField = this.destinationCard.locator('[data-testid="operational-point-ci"]');
this.viaIcon = page.locator('.stdcm-via-icons');
this.viaDeleteButton = page.getByTestId('delete-via-button');
this.originArrival = page.locator('#select-origin-arrival');
this.dateOriginArrival = page.locator('#date-origin-arrival');
this.timeOriginArrival = page.locator('#time-origin-arrival');
this.toleranceOriginArrival = page.locator('#stdcm-tolerance-origin-arrival');
this.destinationArrival = page.locator('#select-destination-arrival');
this.dateDestinationArrival = page.locator('#date-destination-arrival');
this.timeDestinationArrival = page.locator('#time-destination-arrival');
this.closeTimePickerButton = page.locator('.time-picker .close-button');
this.toleranceDestinationArrival = page.locator('#stdcm-tolerance-destination-arrival');
this.closeTolerancePickerButton = page.locator('.tolerance-picker .close-button');
this.warningBox = page.getByTestId('warning-box');
this.suggestionList = page.locator('.suggestions-list');
this.suggestionItems = this.suggestionList.locator('.suggestion-item');
this.suggestionNS = this.suggestionList.locator('.suggestion-item', {
hasText: 'NS North_station',
});
this.suggestionNWS = this.suggestionList.locator('.suggestion-item', {
hasText: 'NWS North_West_station',
});
this.suggestionSS = this.suggestionList.locator('.suggestion-item', {
hasText: 'SS South_station',
});
this.suggestionMES = this.suggestionList.locator('.suggestion-item', {
hasText: 'MES Mid_East_station',
});
this.suggestionMWS = this.suggestionList.locator('.suggestion-item', {
hasText: 'MWS Mid_West_station',
});
this.dynamicOriginCh = this.originCard.locator('[data-testid="operational-point-ch"]');
this.dynamicDestinationCh = this.destinationCard.locator(
'[data-testid="operational-point-ch"]'
);
this.dynamicOriginCi = this.originCard.locator('[data-testid="operational-point-ci"]');
this.dynamicDestinationCi = this.destinationCard.locator(
'[data-testid="operational-point-ci"]'
);
this.simulationStatus = page.getByTestId('simulation-status');
this.simulationList = page.locator('.stdcm-results .simulation-list');
this.incrementButton = page.locator('.minute-button', { hasText: '+1mn' });
this.allViasButton = page.getByTestId('all-vias-button');
this.retainSimulationButton = page.getByTestId('retain-simulation-button');
this.downloadSimulationButton = page.locator('.download-simulation a[download]');
this.downloadSimulationButton = page.locator('.download-simulation a[download]');
this.downloadLink = page.locator('.download-simulation a');
this.startNewQueryButton = page.getByTestId('start-new-query-button');
this.startNewQueryWithDataButton = page.getByTestId('start-new-query-with-data-button');
this.originMarker = this.mapContainer.locator('img[alt="origin"]');
this.destinationMarker = this.mapContainer.locator('img[alt="destination"]');
this.viaMarker = this.mapContainer.locator('img[alt="via"]');
this.mapResultContainer = page.locator('#stdcm-map-result');
this.originResultMarker = this.mapResultContainer.locator('img[alt="origin"]');
this.destinationResultMarker = this.mapResultContainer.locator('img[alt="destination"]');
this.viaResultMarker = this.mapResultContainer.locator('img[alt="via"]');
this.simulationResultTable = page.locator('.simulation-results table.table-results');
this.simulationLengthAndDuration = page.locator(
'.simulation-metadata .total-length-trip-duration'
);
}
// Dynamic selectors for via cards
private getViaCard(viaNumber: number): Locator {
return this.page.locator(`.stdcm-card:has(.stdcm-via-icons:has-text("${viaNumber}"))`);
}
private getViaCH(viaNumber: number): Locator {
return this.getViaCard(viaNumber).locator('[data-testid="operational-point-ch"]');
}
private getViaCI(viaNumber: number): Locator {
return this.getViaCard(viaNumber).locator('[data-testid="operational-point-ci"]');
}
private getViaType(viaNumber: number): Locator {
return this.getViaCard(viaNumber).locator('#type');
}
private getViaStopTime(viaNumber: number): Locator {
return this.getViaCard(viaNumber).locator('#stdcm-via-stop-time');
}
private getViaWarning(viaNumber: number): Locator {
return this.getViaCard(viaNumber).locator('.status-message');
}
private async setMinuteLocator(minuteValue: string) {
const minuteLocator = this.page.locator('.time-grid .minute', { hasText: minuteValue });
await minuteLocator.click();
}
private async setHourLocator(hourValue: string) {
const hourLocator = this.page.locator('.time-grid .hour', { hasText: hourValue });
await hourLocator.click();
}
private getSimulationLengthAndDurationLocator(simulationNumber: number): Locator {
return this.simulationList
.locator('.simulation-metadata .total-length-trip-duration')
.nth(simulationNumber - 1);
}
private getSimulationNameLocator(simulationNumber: number): Locator {
return this.simulationList.locator('.simulation-name').nth(simulationNumber - 1);
}
private async verifySuggestions(expectedSuggestions: string[]) {
await expect(this.suggestionList).toBeVisible();
expect(await this.suggestionItems.count()).toBe(expectedSuggestions.length);
const actualSuggestions = await this.suggestionItems.allTextContents();
expect(actualSuggestions).toEqual(expectedSuggestions);
}
// Verify STDCM elements are visible
async verifyStdcmElementsVisibility() {
const elements = [
this.debugButton,
this.helpButton,
this.notificationHeader,
this.consistCard,
this.originCard,
this.addViaButton,
this.anteriorAddLinkedPathButton,
this.posteriorAddLinkedPathButton,
this.destinationCard,
this.mapContainer,
this.launchSimulationButton,
];
for (const element of elements) {
await expect(element).toBeVisible();
}
}
// Verify all input fields are empty
// Except for speedLimitTags, which has a default value of 'MA100'
async verifyAllDefaultPageFields() {
const emptyFields = [
this.tractionEngineField,
this.towedRollingStockField,
this.tonnageField,
this.lengthField,
this.maxSpeedField,
this.originCiField,
this.destinationCiField,
this.originChField,
this.destinationChField,
];
const { arrivalDate, arrivalTime, tolerance, speedLimitTag } = DEFAULT_DETAILS;
for (const field of emptyFields) await expect(field).toHaveValue('');
await expect(this.originArrival).toHaveValue(ORIGIN_DETAILS.arrivalType.default);
await expect(this.destinationArrival).toHaveValue(DESTINATION_DETAILS.arrivalType.default);
await expect(this.speedLimitTagField).toHaveValue(speedLimitTag);
await expect(this.dateOriginArrival).toHaveValue(arrivalDate);
await expect(this.timeOriginArrival).toHaveValue(arrivalTime);
await expect(this.toleranceOriginArrival).toHaveValue(tolerance);
}
// Add a via card, verify fields, and delete it
async addAndDeletedDefaultVia() {
await this.addViaButton.click();
await this.page.waitForTimeout(EXPLICIT_UI_STABILITY_TIMEOUT); // Wait for the animation to complete
await expect(this.getViaCI(1)).toHaveValue('');
await expect(this.getViaCH(1)).toHaveValue('');
await expect(this.getViaType(1)).toHaveValue(VIA_STOP_TYPES.PASSAGE_TIME);
await this.viaIcon.hover();
await expect(this.viaDeleteButton).toBeVisible();
await this.viaDeleteButton.click();
await expect(this.getViaCI(1)).not.toBeVisible();
await expect(this.getViaCH(1)).not.toBeVisible();
await expect(this.getViaType(1)).not.toBeVisible();
}
// Verify the origin suggestions when searching for north
async verifyOriginNorthSuggestions() {
await this.verifySuggestions(CI_SUGGESTIONS.north);
}
// Verify the destination suggestions when searching for south
async verifyDestinationSouthSuggestions() {
await this.verifySuggestions(CI_SUGGESTIONS.south);
}
// Fill fields with test values in the consist section
async fillAndVerifyConsistDetails(
consistFields: ConsistFields,
tractionEngineTonnage: string,
tractionEngineLength: string,
towedRollingStockTonnage?: string,
towedRollingStockLength?: string
): Promise<void> {
const { tractionEngine, towedRollingStock, tonnage, length, speedLimitTag } = consistFields;
// Generic utility for handling dropdown selection and value verification
const handleAndVerifyDropdown = async (
dropdownField: Locator,
expectedValues: { expectedTonnage: string; expectedLength: string },
selectedValue?: string
) => {
if (!selectedValue) return;
await dropdownField.fill(selectedValue);
await dropdownField.press('ArrowDown');
await dropdownField.press('Enter');
await dropdownField.dispatchEvent('blur');
await expect(dropdownField).toHaveValue(selectedValue);
const { expectedTonnage, expectedLength } = expectedValues;
await expect(this.tonnageField).toHaveValue(expectedTonnage);
await expect(this.lengthField).toHaveValue(expectedLength);
await expect(this.maxSpeedField).toHaveValue(DEFAULT_DETAILS.maxSpeed);
};
// Utility to calculate prefilled values for towed rolling stock
const calculateTowedPrefilledValues = () => {
if (!towedRollingStockTonnage || !towedRollingStockLength) {
return { expectedTonnage: '0', expectedLength: '0' };
}
return {
expectedTonnage: (
parseFloat(towedRollingStockTonnage) + parseFloat(tractionEngineTonnage)
).toString(),
expectedLength: (
parseFloat(towedRollingStockLength) + parseFloat(tractionEngineLength)
).toString(),
};
};
// Calculate prefilled values for the towed rolling stock
const towedPrefilledValues = calculateTowedPrefilledValues();
// Fill and verify traction engine dropdown
await handleAndVerifyDropdown(
this.tractionEngineField,
{
expectedTonnage: tractionEngineTonnage,
expectedLength: tractionEngineLength,
},
tractionEngine
);
// Fill and verify towed rolling stock dropdown
await handleAndVerifyDropdown(
this.towedRollingStockField,
towedPrefilledValues,
towedRollingStock
);
// Fill and verify individual fields
await handleAndVerifyInput(this.tonnageField, tonnage);
await handleAndVerifyInput(this.lengthField, length);
await handleAndVerifyInput(this.maxSpeedField, DEFAULT_DETAILS.maxSpeed);
// Handle optional speed limit tag
if (speedLimitTag) {
await this.speedLimitTagField.selectOption(speedLimitTag);
await expect(this.speedLimitTagField).toHaveValue(speedLimitTag);
}
}
// Fill and verify origin details with suggestions
async fillAndVerifyOriginDetails() {
const {
input,
suggestion,
chValue,
arrivalDate,
arrivalTime,
tolerance,
updatedChValue,
arrivalType,
} = ORIGIN_DETAILS;
// Fill and verify origin CI suggestions
await this.dynamicOriginCi.fill(input);
await this.verifyOriginNorthSuggestions();
await expect(this.suggestionNWS).toBeVisible();
await this.suggestionNWS.click();
const originCiValue = await this.dynamicOriginCi.getAttribute('value');
expect(originCiValue).toContain(suggestion);
// Verify default values
await expect(this.dynamicOriginCh).toHaveValue(chValue);
await expect(this.originArrival).toHaveValue(arrivalType.default);
await expect(this.dateOriginArrival).toHaveValue(arrivalDate);
await expect(this.timeOriginArrival).toHaveValue(arrivalTime);
await expect(this.toleranceOriginArrival).toHaveValue(tolerance);
// Update and verify origin values
await this.dynamicOriginCh.selectOption(updatedChValue);
await expect(this.dynamicOriginCh).toHaveValue(updatedChValue);
await this.originArrival.selectOption(arrivalType.updated);
await expect(this.originArrival).toHaveValue(arrivalType.updated);
// Verify fields are hidden
await expect(this.dateOriginArrival).not.toBeVisible();
await expect(this.timeOriginArrival).not.toBeVisible();
await expect(this.toleranceOriginArrival).not.toBeVisible();
}
// Fill and verify destination details
async fillAndVerifyDestinationDetails() {
const {
input,
suggestion,
chValue,
arrivalDate,
arrivalTime,
tolerance,
arrivalType,
updatedDetails,
} = DESTINATION_DETAILS;
const translations = getTranslations({
en: enTranslations,
fr: frTranslations,
});
// Fill destination input and verify suggestions
await this.dynamicDestinationCi.fill(input);
await this.verifyDestinationSouthSuggestions();
await expect(this.suggestionSS).toBeVisible();
await this.suggestionSS.click();
const destinationCiValue = await this.dynamicDestinationCi.getAttribute('value');
expect(destinationCiValue).toContain(suggestion);
// Verify default values
await expect(this.dynamicDestinationCh).toHaveValue(chValue);
await expect(this.destinationArrival).toHaveValue(arrivalType.default);
await expect(this.warningBox).toContainText(translations.stdcmErrors.noScheduledPoint);
await expect(this.dateDestinationArrival).not.toBeVisible();
await expect(this.timeDestinationArrival).not.toBeVisible();
await expect(this.toleranceDestinationArrival).not.toBeVisible();
// Select 'preciseTime' and verify values
await this.destinationArrival.selectOption(arrivalType.updated);
await expect(this.destinationArrival).toHaveValue(arrivalType.updated);
await expect(this.dateDestinationArrival).toHaveValue(arrivalDate);
await expect(this.timeDestinationArrival).toHaveValue(arrivalTime);
await expect(this.toleranceDestinationArrival).toHaveValue(tolerance);
// Update date and time values
await this.dateDestinationArrival.fill(updatedDetails.date);
await expect(this.dateDestinationArrival).toHaveValue(updatedDetails.date);
await this.timeDestinationArrival.click();
await this.setHourLocator(updatedDetails.hour);
await this.setMinuteLocator(updatedDetails.minute);
await this.incrementButton.dblclick(); // Double-click the +1 minute button to reach 37
await this.closeTimePickerButton.click();
await expect(this.timeDestinationArrival).toHaveValue(updatedDetails.timeValue);
// Update tolerance and verify warning box
await this.fillToleranceField(
updatedDetails.tolerance.negative,
updatedDetails.tolerance.positive,
false
);
await expect(this.warningBox).not.toBeVisible();
}
// Fill origin section
async fillOriginDetailsLight(arrivalTypeOverride: string = '', isPrecise: boolean = false) {
const { input, chValue, arrivalDate, arrivalTime, tolerance, arrivalType } =
LIGHT_ORIGIN_DETAILS;
await this.dynamicOriginCi.fill(input);
await expect(this.suggestionNWS).toBeVisible();
await this.suggestionNWS.click();
if (isPrecise && arrivalTypeOverride) {
await this.originArrival.selectOption(arrivalTypeOverride);
} else {
await expect(this.dynamicOriginCh).toHaveValue(chValue);
await expect(this.originArrival).toHaveValue(arrivalType);
await this.dateOriginArrival.fill(arrivalDate);
await this.timeOriginArrival.fill(arrivalTime);
await this.fillToleranceField(tolerance.negative, tolerance.positive, true);
}
}
// Fill destination section
async fillDestinationDetailsLight() {
const { input, chValue, arrivalType } = LIGHT_DESTINATION_DETAILS;
await this.dynamicDestinationCi.fill(input);
await expect(this.suggestionSS).toBeVisible();
await this.suggestionSS.click();
await expect(this.dynamicDestinationCh).toHaveValue(chValue);
await expect(this.destinationArrival).toHaveValue(arrivalType);
}
async fillToleranceField(minusValue: string, plusValue: string, isOrigin: boolean) {
const toleranceField = isOrigin
? this.toleranceOriginArrival
: this.toleranceDestinationArrival;
await toleranceField.click();
await this.page.getByRole('button', { name: minusValue, exact: true }).click();
await this.page.getByRole('button', { name: plusValue, exact: true }).click();
await expect(toleranceField).toHaveValue(`${minusValue}/${plusValue}`);
await this.closeTolerancePickerButton.click();
}
async fillAndVerifyViaDetails({
viaNumber,
ciSearchText,
}: {
viaNumber: number;
ciSearchText: string;
}): Promise<void> {
const { PASSAGE_TIME, SERVICE_STOP, DRIVER_SWITCH } = VIA_STOP_TYPES;
const { serviceStop, driverSwitch } = VIA_STOP_TIMES;
const translations = getTranslations({
en: enTranslations,
fr: frTranslations,
});
const warning = this.getViaWarning(viaNumber);
// Helper function to fill common fields
const fillVia = async (selectedSuggestion: Locator) => {
await this.addViaButton.nth(viaNumber - 1).click();
expect(await this.addViaButton.count()).toBe(viaNumber + 1);
await expect(this.getViaCI(viaNumber)).toBeVisible();
await this.getViaCI(viaNumber).fill(ciSearchText);
await expect(selectedSuggestion).toBeVisible();
await selectedSuggestion.click();
await expect(this.getViaCH(viaNumber)).toHaveValue(DEFAULT_DETAILS.chValue);
await expect(this.getViaType(viaNumber)).toHaveValue(PASSAGE_TIME);
};
switch (ciSearchText) {
case 'mid_west':
await fillVia(this.suggestionMWS);
break;
case 'mid_east':
await fillVia(this.suggestionMES);
await this.getViaType(viaNumber).selectOption(SERVICE_STOP);
await expect(this.getViaStopTime(viaNumber)).toHaveValue(serviceStop.default);
await this.getViaStopTime(viaNumber).fill(serviceStop.input);
await expect(this.getViaStopTime(viaNumber)).toHaveValue(serviceStop.input);
break;
case 'nS':
await fillVia(this.suggestionNS);
await this.getViaType(viaNumber).selectOption(DRIVER_SWITCH);
await expect(this.getViaStopTime(viaNumber)).toHaveValue(driverSwitch.default);
await this.getViaStopTime(viaNumber).fill(driverSwitch.invalidInput);
await expect(this.getViaStopTime(viaNumber)).toHaveValue(driverSwitch.invalidInput);
await expect(warning).toBeVisible();
expect(await warning.textContent()).toEqual(translations.trainPath.warningMinStopTime);
await this.getViaStopTime(viaNumber).fill(driverSwitch.validInput);
await expect(this.getViaStopTime(viaNumber)).toHaveValue(driverSwitch.validInput);
await expect(warning).not.toBeVisible();
break;
default:
throw new Error(`Unsupported viaSearch value: ${ciSearchText}`);
}
}
// Launch the simulation and check if simulation-related elements are visible
async launchSimulation(): Promise<void> {
await this.launchSimulationButton.waitFor();
await expect(this.launchSimulationButton).toBeEnabled();
await this.launchSimulationButton.click({ force: true });
// Wait for simulation message "Calculation completed"
await this.simulationStatus.waitFor({ timeout: STDCM_SIMULATION_TIMEOUT });
// Check map result container visibility only for Chromium browser
if (this.page.context().browser()?.browserType().name() === 'chromium') {
await expect(this.mapResultContainer).toBeVisible();
}
}
async verifyTableData(tableDataPath: string): Promise<void> {
// Load expected data from JSON file
const jsonData: TableRow[] = readJsonFile(tableDataPath);
// Extract rows from the HTML table and map each row's data to match JSON structure
const tableRows = await this.page.$$eval('.table-results tbody tr', (rows) =>
rows.map((row) => {
const cells = row.querySelectorAll('td');
return {
index: Number(cells[0]?.textContent?.trim()) || 0,
operationalPoint: cells[1]?.textContent?.trim() || '',
code: cells[2]?.textContent?.trim() || '',
endStop: cells[3]?.textContent?.trim() || '',
passageStop: cells[4]?.textContent?.trim() || '',
startStop: cells[5]?.textContent?.trim() || '',
weight: cells[6]?.textContent?.trim() || '',
refEngine: cells[7]?.textContent?.trim() || '',
};
})
);
// Compare JSON data and table rows by index for consistency
jsonData.forEach((jsonRow, index) => {
const tableRow = tableRows[index];
// Check if the row exists in the HTML table
if (!tableRow) {
logger.error(`Row ${index + 1} is missing in the HTML table`);
return;
}
expect(tableRow.operationalPoint).toBe(jsonRow.operationalPoint);
expect(tableRow.code).toBe(jsonRow.code);
expect(tableRow.endStop).toBe(jsonRow.endStop);
expect(tableRow.passageStop).toBe(jsonRow.passageStop);
expect(tableRow.startStop).toBe(jsonRow.startStop);
expect(tableRow.weight).toBe(jsonRow.weight);
expect(tableRow.refEngine).toBe(jsonRow.refEngine);
});
}
async displayAllOperationalPoints() {
await this.allViasButton.click();
}
async retainSimulation() {
await this.retainSimulationButton.click();
await expect(this.downloadSimulationButton).toBeVisible();
await expect(this.downloadSimulationButton).toBeEnabled();
await expect(this.startNewQueryButton).toBeVisible();
await expect(this.startNewQueryWithDataButton).toBeVisible();
}
async downloadSimulation(downloadDir: string): Promise<void> {
// Wait until there are no network requests for stability
await this.page.waitForLoadState('networkidle');
// Get the download link element and suggested filename
const suggestedFilename = await this.downloadLink.getAttribute('download');
expect(suggestedFilename).toMatch(/^Stdcm.*\.pdf$/);
const downloadPath = path.join(downloadDir, suggestedFilename!);
await fs.promises.mkdir(downloadDir, { recursive: true });
// Get the file content from the `blob:` URL
const fileContent = await this.downloadSimulationButton.evaluate(async (el) => {
if (!(el instanceof HTMLAnchorElement)) {
throw new Error('Element is not an anchor tag');
}
const response = await fetch(el.href);
if (!response.ok) {
throw new Error(`Failed to fetch the blob: ${response.status} ${response.statusText}`);
}
const buffer = await response.arrayBuffer();
return Array.from(new Uint8Array(buffer));
});
// Write the file to the local file system
await fs.promises.writeFile(downloadPath, Buffer.from(fileContent));
logger.info(`The PDF was successfully downloaded to: ${downloadPath}`);
}
async startNewQuery() {
await this.startNewQueryButton.click();
}
async mapMarkerVisibility() {
await expect(this.originMarker).toBeVisible();
await expect(this.destinationMarker).toBeVisible();
await expect(this.viaMarker).toBeVisible();
}
async mapMarkerResultVisibility() {
await expect(this.originResultMarker).toBeVisible();
await expect(this.destinationResultMarker).toBeVisible();
await expect(this.viaResultMarker).toBeVisible();
}
async verifySimulationDetails({
simulationNumber,
simulationLengthAndDuration,
}: {
simulationNumber: number;
simulationLengthAndDuration?: string | null;
}): Promise<void> {
const translations = getTranslations({
en: enTranslations,
fr: frTranslations,
});
const noCapacityLengthAndDuration = '— ';
// Determine expected simulation name
const isResultTableVisible = await this.simulationResultTable.isVisible();
const expectedSimulationName = isResultTableVisible
? `Simulation n°${simulationNumber}`
: translations.simulation.results.simulationName.withoutOutputs;
// Validate simulation name
const actualSimulationName =
await this.getSimulationNameLocator(simulationNumber).textContent();
expect(actualSimulationName).toEqual(expectedSimulationName);
// Determine expected length and duration
const expectedLengthAndDuration = isResultTableVisible
? simulationLengthAndDuration
: noCapacityLengthAndDuration;
const actualLengthAndDuration =
await this.getSimulationLengthAndDurationLocator(simulationNumber).textContent();
// Validate length and duration
expect(actualLengthAndDuration).toEqual(expectedLengthAndDuration);
}
}
export default STDCMPage;