@ebertjendustries/cstestwrapper 1.0.13 → 1.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs DELETED
@@ -1,1858 +0,0 @@
1
- // src/localisation/TestLocalisation.ts
2
- var TestLocalisation = class {
3
- };
4
-
5
- // src/components/AbstractComponentTesting.ts
6
- import wrapper from "@cloudscape-design/components/test-utils/dom";
7
- import { screen, waitForElementToBeRemoved } from "@testing-library/react";
8
- import { act } from "react";
9
- import { expect } from "vitest";
10
- import { FORM_FIELD_ID_SUFFIX } from "@ebertjendustries/cswrapper";
11
- var AbstractComponentTesting = class _AbstractComponentTesting {
12
- constructor(elementSpec, view, findFunction) {
13
- this.elementSpec = elementSpec;
14
- this.view = view;
15
- this.findFunction = findFunction;
16
- if (elementSpec.getDataTestId().indexOf(".") !== -1) {
17
- throw new Error("Data test ids to be used as selected must not contain dots. Found dots in following data-testid: " + elementSpec.getDataTestId());
18
- }
19
- }
20
- static expectEnabled(element, msg) {
21
- if (element.hasAttribute("aria-disabled")) {
22
- expect(element, msg).toHaveAttribute("aria-disabled", "false");
23
- } else {
24
- expect(element, msg).toBeEnabled();
25
- }
26
- }
27
- static expectDisabled(element, msg) {
28
- if (element.hasAttribute("aria-disabled")) {
29
- expect(element, msg).toHaveAttribute("aria-disabled", "true");
30
- } else {
31
- expect(element, msg).toBeDisabled();
32
- }
33
- }
34
- static doFindElement(dataTestId, findFunction) {
35
- return findFunction(`[data-testid*=${dataTestId}]`);
36
- }
37
- expectFormFieldLabelDisplayed() {
38
- expect(this.getFormFieldWrapper().findLabel()).not.toBeNull();
39
- }
40
- expectFormFieldLabelNotDisplayed() {
41
- if (this.getFormFieldWrapper() !== null) {
42
- expect(this.getFormFieldWrapper().findLabel()).toBeNull();
43
- } else {
44
- expect(this.getFormFieldWrapper()).toBeNull();
45
- }
46
- }
47
- getElement() {
48
- const element = this.getElementWrapper();
49
- return this.assertElement(this.elementSpec.getDataTestId(), () => element.getElement());
50
- }
51
- queryElement() {
52
- const element = _AbstractComponentTesting.doFindElement(this.elementSpec.getDataTestId(), this.findFunction);
53
- if (element === null) {
54
- return null;
55
- } else {
56
- const htmlElement = element.getElement();
57
- if (htmlElement === void 0) {
58
- return null;
59
- }
60
- return htmlElement;
61
- }
62
- }
63
- awaitElement() {
64
- return screen.findByTestId(this.elementSpec.getDataTestId());
65
- }
66
- async awaitPresent() {
67
- expect(await this.awaitElement()).toBeInTheDocument();
68
- }
69
- expectPresent() {
70
- expect(this.getElement()).toBeInTheDocument();
71
- }
72
- expectNotPresent() {
73
- expect(this.queryElement()).toBeNull();
74
- }
75
- expectEnabled() {
76
- _AbstractComponentTesting.expectEnabled(this.getElement(), this.msgForExpect());
77
- }
78
- expectDisabled() {
79
- _AbstractComponentTesting.expectDisabled(this.getElement(), this.msgForExpect());
80
- }
81
- click() {
82
- act(() => {
83
- const element = this.assertElement(this.elementSpec.getDataTestId(), (dataTestId) => _AbstractComponentTesting.doFindElement(dataTestId, this.findFunction));
84
- element.click();
85
- });
86
- }
87
- expectReadOnly() {
88
- expect(this.getElement()).toHaveAttribute("readonly", "true");
89
- }
90
- expectNotReadOnly() {
91
- expect(this.getElement()).not.toHaveAttribute("readonly");
92
- }
93
- expectChecked() {
94
- expect(this.getElement(), this.msgForExpect()).toBeChecked();
95
- }
96
- expectNotChecked() {
97
- expect(this.getElement(), this.msgForExpect()).not.toBeChecked();
98
- }
99
- expectCheckState(checked) {
100
- if (checked) {
101
- this.expectChecked();
102
- } else {
103
- this.expectNotChecked();
104
- }
105
- }
106
- expectContent(text) {
107
- expect(this.getElement(), this.msgForExpect()).toHaveTextContent(text);
108
- }
109
- async awaitNotPresent() {
110
- await waitForElementToBeRemoved(() => this.queryElement());
111
- }
112
- getFormFieldWrapper() {
113
- return _AbstractComponentTesting.doFindElement(this.elementSpec.getDataTestId() + FORM_FIELD_ID_SUFFIX, (dataTestId) => wrapper().findFormField(dataTestId));
114
- }
115
- assertElement(dataTestId, getterFunction) {
116
- const element = getterFunction(dataTestId);
117
- if (element === null || element === void 0) {
118
- throw new Error(this.elementNotFoundErrorMessage(dataTestId));
119
- }
120
- return element;
121
- }
122
- elementNotFoundErrorMessage(dataTestId) {
123
- return `Element with data-testid ${dataTestId} not found`;
124
- }
125
- getElementWrapper() {
126
- return this.assertElement(this.elementSpec.getDataTestId(), (dataTestId) => _AbstractComponentTesting.doFindElement(dataTestId, this.findFunction));
127
- }
128
- msgForExpect(index, customSuffix) {
129
- const indexPart = index !== void 0 ? `[${index}]` : "";
130
- const suffixPart = customSuffix !== void 0 ? ` - ${customSuffix}` : "";
131
- return `${this.constructor.name}<data-testid=${this.elementSpec.getDataTestId()}>${indexPart}${suffixPart}`;
132
- }
133
- };
134
-
135
- // src/components/AbstractInputTesting.ts
136
- import { waitFor } from "@testing-library/react";
137
- import { ElementValidityLevel } from "@ebertjendustries/cswrapper";
138
- import { FieldSpec } from "@ebertjendustries/cswrapper";
139
- import { expect as expect2 } from "vitest";
140
- var AbstractInputTesting = class extends AbstractComponentTesting {
141
- clear() {
142
- this.setStringValue("");
143
- }
144
- async forceTooLongValidationMessage(repeatedString) {
145
- const inputValue = (repeatedString === void 0 ? "test" : repeatedString).repeat(this.elementSpec.maxLength + 2);
146
- this.setStringValue(inputValue);
147
- const localiser = this.view.getLocaliser();
148
- const fieldValidityFunction = localiser.getFieldValidityLocalisationFunction();
149
- await this.expectErrorMessage(fieldValidityFunction(this.elementSpec, ElementValidityLevel.MAX_LENGTH_EXCEEDED));
150
- }
151
- async awaitMandatoryMissing() {
152
- const localiser = this.view.getLocaliser();
153
- const fieldValidityFunction = localiser.getFieldValidityLocalisationFunction();
154
- await this.expectErrorMessage(fieldValidityFunction(new FieldSpec("", true), ElementValidityLevel.REQUIRED_VALUE_IS_NOT_PRESENT));
155
- }
156
- expectReadOnly() {
157
- expect2(this.getNativeHTMLInput().readOnly).toBeTruthy();
158
- }
159
- expectNotReadOnly() {
160
- expect2(this.getNativeHTMLInput().readOnly).toBeFalsy();
161
- }
162
- expectEmpty() {
163
- expect2(this.getNativeHTMLInput()).toHaveValue(null);
164
- }
165
- overwriteAndVerify(value) {
166
- this.setStringValue(value === void 0 ? "" : value.toString());
167
- this.expectValue(value);
168
- }
169
- expectEnabled() {
170
- expect2(this.getNativeHTMLInput()).toBeEnabled();
171
- }
172
- expectDisabled() {
173
- expect2(this.getNativeHTMLInput()).toBeDisabled();
174
- }
175
- async expectErrorMessage(message) {
176
- await waitFor(() => expect2(this.getFormFieldWrapper().findError()).not.toBeNull());
177
- expect2(this.getFormFieldWrapper().findError().getElement()).toHaveTextContent(message);
178
- }
179
- };
180
-
181
- // src/components/AbstractSelectTesting.ts
182
- import { waitFor as waitFor2 } from "@testing-library/react";
183
- import { act as act2 } from "react";
184
- import { expect as expect3 } from "vitest";
185
- var AbstractSelectTesting = class extends AbstractComponentTesting {
186
- constructor(fieldSpec, view, findFunction, expandToViewport) {
187
- super(fieldSpec, view, findFunction);
188
- this.expandToViewport = expandToViewport;
189
- }
190
- async expectSelectedEnumEntries(enumFactory, selectedEntries) {
191
- const localiser = this.view.getLocaliser();
192
- await this.expectSelectedEntries(selectedEntries.map((entry) => localiser.getEnumLabel(enumFactory, entry)), enumFactory.values.length);
193
- }
194
- async expectSelectedEntries(selectedEntries, totalEntryCount) {
195
- const selectWrapper = await this.openDropdown();
196
- const selectedOptions = this.getDropdown(selectWrapper).findSelectedOptions();
197
- const selectedOptionsText = selectedOptions.map((selectedOption) => selectedOption.findLabel().getElement().textContent);
198
- console.log(`CURRENTLY selected options = ${selectedOptionsText}, EXPECTED selected options = ${selectedEntries}`);
199
- const indexDiff = selectedEntries.length === totalEntryCount ? 1 : 0;
200
- expect3(selectedOptions, this.msgForExpect()).toHaveLength(selectedEntries.length + indexDiff);
201
- const selectedEntriesSet = /* @__PURE__ */ new Set();
202
- selectedEntries.forEach((entry) => selectedEntriesSet.add(entry));
203
- for (let index = indexDiff; index < selectedOptionsText.length; index++) {
204
- const selectedOption = selectedOptionsText[index];
205
- const hasElement = selectedEntriesSet.has(selectedOption);
206
- if (!hasElement) {
207
- console.log(`Expected element at index ${index} to be selected: ${selectedOption}.`);
208
- }
209
- expect3(hasElement, this.msgForExpect(index)).toBeTruthy();
210
- }
211
- await this.closeDropdown(selectWrapper);
212
- }
213
- /**
214
- * Expects entries in the array.
215
- *
216
- * @param entries The expected entry labels
217
- * @param selectedIndices The selected entry indices
218
- *
219
- * The selected indices are zero-based and DO NOT consider the "Select all" entry. I.e. the first entry after
220
- * "Select all" has index = 0.
221
- */
222
- async expectEntries(entries, selectedIndices) {
223
- selectedIndices = selectedIndices.sort((a, b) => a - b);
224
- expect3(await this.awaitElement(), this.msgForExpect()).toBeInTheDocument();
225
- const selectWrapper = await this.openDropdown();
226
- const options = this.getDropdown(selectWrapper).findOptions();
227
- expect3(options, this.msgForExpect()).toHaveLength(entries.length);
228
- const selectedOptions = this.getDropdown(selectWrapper).findSelectedOptions();
229
- const indexDiff = entries.length === selectedIndices.length ? 1 : 0;
230
- expect3(selectedOptions, this.msgForExpect()).toHaveLength(selectedIndices.length + indexDiff);
231
- for (let index = indexDiff; index < selectedOptions.length; index++) {
232
- const selectedOption = selectedOptions[index];
233
- expect3(selectedOption.findLabel().getElement().textContent, this.msgForExpect(index)).toBe(entries[selectedIndices[index - indexDiff]]);
234
- }
235
- await this.closeDropdown(selectWrapper);
236
- }
237
- async expectEnumEntries(enumFactory, selectedEnums, except) {
238
- const totalEnums = enumFactory.values.filter((e) => except === void 0 || except.indexOf(e) === -1);
239
- const selectedOptionIndices = selectedEnums.map((i) => totalEnums.findIndex((e) => e === i));
240
- const localiser = this.view.getLocaliser();
241
- await this.expectEntries(
242
- totalEnums.map((e) => localiser.getEnumLabel(enumFactory, e)),
243
- selectedOptionIndices
244
- );
245
- }
246
- async selectOrDeselect(clickedIndices) {
247
- expect3(await this.awaitElement(), this.msgForExpect()).toBeInTheDocument();
248
- const sortedIndices = clickedIndices.sort((a, b) => b - a);
249
- const selectWrapper = await this.openDropdown();
250
- for (let index = 0; index < sortedIndices.length; index++) {
251
- const clickedIndex = sortedIndices[index];
252
- act2(() => selectWrapper.selectOption(clickedIndex + 1, this.getOptions()));
253
- }
254
- await this.closeDropdown(selectWrapper);
255
- }
256
- // ATTENTION! Do NOT use with enum single select! It will lead to failing tests as it does not change selection.
257
- async select(entries) {
258
- console.log("SELECTING options = " + entries);
259
- const indicesToSelect = [];
260
- const indicesToDeselect = [];
261
- const selectWrapper = await this.openDropdown();
262
- const selectedOptionValues = this.optionsToEntrySet(this.getDropdown(selectWrapper).findSelectedOptions());
263
- const allOptions = this.getDropdown(selectWrapper).findOptions();
264
- await this.closeDropdown(selectWrapper);
265
- const optionValuesToSelect = /* @__PURE__ */ new Set();
266
- entries.forEach((entry) => optionValuesToSelect.add(entry));
267
- for (let index = 0; index < allOptions.length; index++) {
268
- const optionValue = allOptions[index].getElement().textContent;
269
- if (optionValuesToSelect.has(optionValue) && !selectedOptionValues.has(optionValue)) {
270
- indicesToSelect.push(index);
271
- } else if (!optionValuesToSelect.has(optionValue) && selectedOptionValues.has(optionValue)) {
272
- indicesToDeselect.push(index);
273
- }
274
- }
275
- await this.selectOrDeselect(indicesToSelect);
276
- await this.selectOrDeselect(indicesToDeselect);
277
- await this.closeDropdown(await this.openDropdown());
278
- }
279
- async openDropdown() {
280
- const selectWrapper = this.getElementWrapper();
281
- act2(() => selectWrapper.openDropdown());
282
- await waitFor2(() => expect3(this.getDropdown(selectWrapper).findOptions().length, this.msgForExpect()).toBeGreaterThan(0));
283
- return selectWrapper;
284
- }
285
- async closeDropdown(selectWrapper) {
286
- act2(() => selectWrapper.closeDropdown(this.getOptions()));
287
- if (!this.expandToViewport) {
288
- await waitFor2(() => expect3(this.getDropdown(selectWrapper).findOptions().length, this.msgForExpect()).toBe(0));
289
- }
290
- }
291
- async awaitHasSelectedEntryCount(selectedEntryCount, totalEntryCount) {
292
- const selectWrapper = await this.openDropdown();
293
- const options = this.getDropdown(selectWrapper).findSelectedOptions();
294
- if (selectedEntryCount === totalEntryCount) {
295
- expect3(options, this.msgForExpect()).toHaveLength(selectedEntryCount + 1);
296
- } else {
297
- expect3(options, this.msgForExpect()).toHaveLength(selectedEntryCount);
298
- }
299
- await this.closeDropdown(selectWrapper);
300
- }
301
- getOptions() {
302
- return this.expandToViewport === void 0 ? void 0 : { expandToViewport: this.expandToViewport };
303
- }
304
- getDropdown(selectWrapper) {
305
- return selectWrapper.findDropdown(this.getOptions());
306
- }
307
- optionsToEntrySet(options) {
308
- const entriesSet = /* @__PURE__ */ new Set();
309
- options.forEach((option) => entriesSet.add(option.getElement().textContent));
310
- return entriesSet;
311
- }
312
- };
313
-
314
- // src/views/AbstractViewTesting.tsx
315
- import { ViewSpec } from "@ebertjendustries/cswrapper";
316
-
317
- // src/components/MultiselectTesting.ts
318
- import wrapper2 from "@cloudscape-design/components/test-utils/dom";
319
- var MultiselectTesting = class extends AbstractSelectTesting {
320
- constructor(fieldSpec, view, expandToViewport) {
321
- super(fieldSpec, view, (selector) => wrapper2().findMultiselect(selector), expandToViewport);
322
- this.view = view;
323
- }
324
- };
325
-
326
- // src/components/SelectTesting.ts
327
- import wrapper3 from "@cloudscape-design/components/test-utils/dom";
328
- import { expect as expect4 } from "vitest";
329
- var SelectTesting = class extends AbstractSelectTesting {
330
- constructor(fieldSpec, view, expandToViewport) {
331
- super(fieldSpec, view, (selector) => wrapper3().findSelect(selector), expandToViewport);
332
- this.view = view;
333
- }
334
- expectEnabled() {
335
- expect4(this.getElementWrapper().isDisabled(), this.msgForExpect()).toBeFalsy();
336
- }
337
- expectDisabled() {
338
- expect4(this.getElementWrapper().isDisabled(), this.msgForExpect()).toBeTruthy();
339
- }
340
- };
341
-
342
- // src/components/InputTesting.ts
343
- import wrapper4 from "@cloudscape-design/components/test-utils/dom";
344
- import { act as act3 } from "react";
345
- import { ElementValidityLevel as ElementValidityLevel2 } from "@ebertjendustries/cswrapper";
346
- import { expect as expect5 } from "vitest";
347
- var StringInputTesting = class extends AbstractInputTesting {
348
- constructor(fieldSpec, view) {
349
- super(fieldSpec, view, (selector) => wrapper4().findInput(selector));
350
- this.view = view;
351
- }
352
- setStringValue(value) {
353
- act3(() => {
354
- this.getElementWrapper().setInputValue(value === void 0 ? "" : value);
355
- });
356
- }
357
- expectValue(value) {
358
- expect5(this.getNativeHTMLInput()).toHaveValue(value === void 0 ? "" : value);
359
- }
360
- getNativeHTMLInput() {
361
- return this.getElementWrapper().findNativeInput().getElement();
362
- }
363
- };
364
- var NumberInputTesting = class extends AbstractInputTesting {
365
- constructor(fieldSpec, view) {
366
- super(fieldSpec, view, (selector) => wrapper4().findInput(selector));
367
- this.view = view;
368
- }
369
- setStringValue(value) {
370
- act3(() => {
371
- if (typeof value === "number") {
372
- this.getElementWrapper().setInputValue(value.toString());
373
- } else {
374
- this.getElementWrapper().setInputValue(value === void 0 ? "" : value);
375
- }
376
- });
377
- }
378
- async forceSmallerThanLowerBoundMessage() {
379
- const inputValue = this.elementSpec.minValue - 1;
380
- this.setStringValue(inputValue.toString());
381
- const localiser = this.view.getLocaliser();
382
- const fieldValidityFunction = localiser.getFieldValidityLocalisationFunction();
383
- await this.expectErrorMessage(fieldValidityFunction(this.elementSpec, ElementValidityLevel2.LOWER_BOUND_ONLY_TOO_SMALL));
384
- }
385
- expectValue(value) {
386
- expect5(this.getNativeHTMLInput()).toHaveValue(value === void 0 ? null : value);
387
- }
388
- getNativeHTMLInput() {
389
- return this.getElementWrapper().findNativeInput().getElement();
390
- }
391
- };
392
- var DatePickerTesting = class extends AbstractInputTesting {
393
- constructor(fieldSpec, view) {
394
- super(fieldSpec, view, (selector) => wrapper4().findDatePicker(selector));
395
- this.view = view;
396
- }
397
- setStringValue(value) {
398
- act3(() => {
399
- this.getElementWrapper().setInputValue(value === void 0 ? "" : value.replaceAll("-", "/"));
400
- });
401
- }
402
- expectValue(value) {
403
- if (value === void 0) {
404
- this.expectEmpty();
405
- } else {
406
- expect5(this.getNativeHTMLInput()).toHaveValue(value.replaceAll("-", "/"));
407
- }
408
- }
409
- getNativeHTMLInput() {
410
- return this.getElementWrapper().findNativeInput().getElement();
411
- }
412
- };
413
-
414
- // src/components/TableTesting.ts
415
- import wrapper5 from "@cloudscape-design/components/test-utils/dom";
416
- import { waitFor as waitFor3 } from "@testing-library/react";
417
- import { act as act4 } from "react";
418
- import { expect as expect6 } from "vitest";
419
- var TableTesting = class extends AbstractComponentTesting {
420
- constructor(fieldSpec, view) {
421
- super(fieldSpec, view, (selector) => wrapper5().findTable(selector));
422
- this.view = view;
423
- }
424
- expectSelectCount(expectedSelectCount) {
425
- const selectedRows = this.getElementWrapper().findSelectedRows();
426
- expect6(selectedRows).toHaveLength(expectedSelectCount);
427
- }
428
- getRowCount() {
429
- return this.getElementWrapper().findRows().length;
430
- }
431
- selectAllItems() {
432
- act4(() => this.getElementWrapper().findSelectAllTrigger().click());
433
- }
434
- expectSelectedItems(selectedRowIndices) {
435
- const allItems = this.getElementWrapper().findRows();
436
- const selectedItems = this.getElementWrapper().findSelectedRows();
437
- for (let index = 0; index < allItems.length; index++) {
438
- if (selectedRowIndices.indexOf(index) !== -1) {
439
- const item = allItems[index];
440
- expect6(selectedItems).toContainEqual(item);
441
- }
442
- }
443
- }
444
- expectUnselectedItems(unselectedRowIndices) {
445
- const allItems = this.getElementWrapper().findRows();
446
- const selectedItems = this.getElementWrapper().findSelectedRows();
447
- for (let index = 0; index < allItems.length; index++) {
448
- if (unselectedRowIndices.indexOf(index) !== -1) {
449
- const item = allItems[index];
450
- expect6(selectedItems).not.toContain(item);
451
- }
452
- }
453
- }
454
- selectItems(clickedRowIndices) {
455
- for (let i = 0; i < clickedRowIndices.length; i++) {
456
- const clickedIndex = clickedRowIndices[i];
457
- const selectionArea = this.assertElement((clickedIndex + 1).toString(), () => this.getElementWrapper().findRowSelectionArea(clickedIndex + 1));
458
- act4(() => {
459
- selectionArea.click();
460
- });
461
- }
462
- }
463
- printRow(rowIndex, columnCount) {
464
- let row = "";
465
- for (let colIndex = 0; colIndex < columnCount; colIndex++) {
466
- row = row + this.getElementWrapper().findBodyCell(rowIndex + 1, colIndex + 1).getElement().textContent + "; ";
467
- }
468
- console.log(`ROW CONTENT (index = ${rowIndex}) = ${row}`);
469
- }
470
- expectCellContent(rowIndex, colIndex, content) {
471
- expect6(this.getElementWrapper().findBodyCell(rowIndex + 1, colIndex + 1).getElement()).toHaveTextContent(content);
472
- }
473
- expectTableContent(content) {
474
- expect6(this.getRowCount()).toBe(content.length);
475
- for (let rowIndex = 0; rowIndex < content.length; rowIndex++) {
476
- this.expectRowContent(rowIndex, content[rowIndex]);
477
- }
478
- }
479
- expectRowContent(rowIndex, content) {
480
- for (let colIndex = 0; colIndex < content.length; colIndex++) {
481
- const cellContent = content[colIndex];
482
- this.expectCellContent(rowIndex, colIndex, cellContent);
483
- }
484
- }
485
- async editCellWithConfirm(rowIndex, colIndex, editSteps) {
486
- await this.editCell(rowIndex, colIndex, editSteps, () => this.getElementWrapper().findEditingCellSaveButton());
487
- }
488
- async editCellWithCancel(rowIndex, colIndex, editSteps) {
489
- await this.editCell(rowIndex, colIndex, editSteps, () => this.getElementWrapper().findEditingCellCancelButton());
490
- }
491
- expectNotContainedInAnyRow(colIndex, content) {
492
- const rowCount = this.getRowCount();
493
- for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
494
- expect6(this.getElementWrapper().findBodyCell(rowIndex + 1, colIndex + 1).getElement()).not.toHaveTextContent(content);
495
- }
496
- }
497
- async awaitLoading() {
498
- await waitFor3(() => expect6(this.getElementWrapper().findLoadingText()).not.toBeNull());
499
- }
500
- async awaitNotLoading() {
501
- await waitFor3(() => expect6(this.getElementWrapper().findLoadingText()).toBeNull());
502
- }
503
- changeColumnSorting(columnHeader) {
504
- const column = this.getElementWrapper().findColumnHeaders().findIndex((header) => header.getElement().textContent === columnHeader);
505
- const sortButton = this.getElementWrapper().findColumnSortingArea(column + 1);
506
- act4(() => sortButton.click());
507
- }
508
- expectSortedBy(columnHeader, desc) {
509
- const descSorted = this.getElementWrapper().findDescSortedColumn();
510
- const ascSorted = this.getElementWrapper().findAscSortedColumn();
511
- if (desc) {
512
- expect6(descSorted).not.toBeNull();
513
- expect6(descSorted.getElement().textContent).toBe(columnHeader);
514
- } else {
515
- expect6(ascSorted).not.toBeNull();
516
- expect6(ascSorted.getElement().textContent).toBe(columnHeader);
517
- }
518
- }
519
- async editCell(rowIndex, colIndex, editSteps, findLeaveButton) {
520
- await waitFor3(() => expect6(this.getElementWrapper().findEditCellButton(rowIndex + 1, colIndex + 1)).not.toBeNull());
521
- act4(() => this.getElementWrapper().findEditCellButton(rowIndex + 1, colIndex + 1).click());
522
- await waitFor3(() => expect6(findLeaveButton()).not.toBeNull());
523
- await editSteps();
524
- act4(() => findLeaveButton().click());
525
- await waitFor3(() => expect6(this.getElementWrapper().findEditCellButton(rowIndex + 1, colIndex + 1)).not.toBeNull());
526
- }
527
- };
528
-
529
- // src/components/WizardTesting.ts
530
- import wrapper6 from "@cloudscape-design/components/test-utils/dom";
531
- import { act as act5 } from "react";
532
- var WizardTesting = class extends AbstractComponentTesting {
533
- constructor(fieldSpec, view) {
534
- super(fieldSpec, view, (selector) => wrapper6().findWizard(selector));
535
- this.view = view;
536
- }
537
- cancel() {
538
- act5(() => this.getElementWrapper().findCancelButton().click());
539
- }
540
- skip() {
541
- const skipButton = this.assertElement(this.elementSpec.getDataTestId() + "SkipButton", () => this.getElementWrapper().findSkipToButton());
542
- act5(() => skipButton.click());
543
- }
544
- prev() {
545
- const prevButton = this.assertElement(this.elementSpec.getDataTestId() + "PrevButton", () => this.getElementWrapper().findPreviousButton());
546
- act5(() => prevButton.click());
547
- }
548
- next() {
549
- act5(() => this.getElementWrapper().findPrimaryButton().click());
550
- }
551
- confirm() {
552
- this.next();
553
- }
554
- goToStep(stepIndex) {
555
- act5(() => this.getElementWrapper().findMenuNavigationLinks()[stepIndex].click());
556
- }
557
- };
558
-
559
- // src/components/ButtonTesting.ts
560
- import wrapper7 from "@cloudscape-design/components/test-utils/dom";
561
- import { waitFor as waitFor4 } from "@testing-library/react";
562
- import { expect as expect7 } from "vitest";
563
- var ButtonTesting = class extends AbstractComponentTesting {
564
- constructor(fieldSpec, view) {
565
- super(fieldSpec, view, (selector) => wrapper7().findButton(selector));
566
- this.view = view;
567
- }
568
- async awaitLoading() {
569
- await waitFor4(() => expect7(this.getElementWrapper().findLoadingIndicator()).not.toBeNull());
570
- }
571
- async awaitNotLoading() {
572
- await waitFor4(() => expect7(this.getElementWrapper().findLoadingIndicator()).toBeNull());
573
- }
574
- async clickAndWaitForLoadingDone() {
575
- this.click();
576
- await this.awaitLoading();
577
- await this.awaitNotLoading();
578
- }
579
- };
580
-
581
- // src/components/ButtonDropdownTesting.ts
582
- import wrapper8 from "@cloudscape-design/components/test-utils/dom";
583
- import { waitFor as waitFor5 } from "@testing-library/react";
584
- import { act as act6 } from "react";
585
- import { expect as expect8 } from "vitest";
586
- var ButtonDropdownTesting = class extends AbstractComponentTesting {
587
- constructor(fieldSpec, view) {
588
- super(fieldSpec, view, (selector) => wrapper8().findButtonDropdown(selector));
589
- this.view = view;
590
- }
591
- async openDropdown() {
592
- act6(() => this.getElementWrapper().openDropdown());
593
- await waitFor5(() => expect8(this.getDropdown()).not.toBeNull());
594
- }
595
- async clickItem(dataTestId) {
596
- await this.openDropdown();
597
- act6(() => {
598
- this.getElementWrapper().findItemById(dataTestId).click();
599
- });
600
- }
601
- getDropdown() {
602
- return this.getElementWrapper().findOpenDropdown();
603
- }
604
- };
605
-
606
- // src/components/ModalTesting.ts
607
- import wrapper9 from "@cloudscape-design/components/test-utils/dom";
608
- import { waitFor as waitFor6 } from "@testing-library/react";
609
- import { act as act7 } from "react";
610
- import { expect as expect9 } from "vitest";
611
- var ModalTesting = class extends AbstractComponentTesting {
612
- constructor(viewSpec, view) {
613
- super(viewSpec, view, (selector) => wrapper9().findModal(selector));
614
- this.view = view;
615
- }
616
- expectHidden() {
617
- expect9(this.getElementWrapper().isVisible()).toBeFalsy();
618
- }
619
- expectVisible() {
620
- expect9(this.getElementWrapper().isVisible()).toBeTruthy();
621
- }
622
- async awaitVisible() {
623
- return waitFor6(() => expect9(this.getElementWrapper().isVisible()).toBeTruthy());
624
- }
625
- async awaitHidden() {
626
- return waitFor6(() => expect9(this.getElementWrapper().isVisible()).toBeFalsy());
627
- }
628
- dismiss() {
629
- act7(() => {
630
- this.getElementWrapper().findDismissButton().click();
631
- });
632
- }
633
- };
634
-
635
- // src/components/RatingTesting.ts
636
- import { ElementWrapper as ElementWrapper4 } from "@cloudscape-design/test-utils-core/dom";
637
- import { screen as screen2 } from "@testing-library/react";
638
- import { act as act8 } from "react";
639
- import { getEnumRatingLabel, getEnumRatingValues } from "@ebertjendustries/cswrapper";
640
- import { expect as expect10 } from "vitest";
641
- var RatingTesting = class extends AbstractComponentTesting {
642
- constructor(viewSpec, view, factory, toOrderNumber) {
643
- super(viewSpec, view, () => {
644
- const element = screen2.queryByLabelText(getEnumRatingValues(factory, toOrderNumber)[0].toString());
645
- if (element === null) {
646
- return null;
647
- }
648
- return new ElementWrapper4(element);
649
- });
650
- this.view = view;
651
- this.enumValuesInOrder = getEnumRatingValues(factory, toOrderNumber);
652
- }
653
- static mockBoundingBox() {
654
- window.SVGElement.prototype.getBBox = () => ({
655
- x: 0,
656
- y: 0,
657
- width: 0,
658
- height: 0
659
- });
660
- }
661
- static unmockBoundingBox() {
662
- delete window.SVGElement.prototype.getBBox;
663
- }
664
- expectSelected(selectedEnum) {
665
- expect10(this.getByLabelText(selectedEnum)).toBeChecked();
666
- }
667
- expectAllUnselected() {
668
- for (const element of this.enumValuesInOrder.slice(1)) {
669
- expect10(this.getByLabelText(element)).not.toBeChecked();
670
- }
671
- }
672
- select(selectedEnum) {
673
- act8(() => {
674
- this.getByLabelText(selectedEnum).click();
675
- });
676
- }
677
- unselectAll() {
678
- act8(() => {
679
- this.getByLabelText(this.enumValuesInOrder[1]).click();
680
- });
681
- act8(() => {
682
- this.getByLabelText(this.enumValuesInOrder[1]).click();
683
- });
684
- }
685
- expectEnabled() {
686
- AbstractComponentTesting.expectEnabled(this.getByLabelText(this.enumValuesInOrder[1]), this.msgForExpect());
687
- }
688
- expectDisabled() {
689
- AbstractComponentTesting.expectDisabled(this.getByLabelText(this.enumValuesInOrder[1]), this.msgForExpect());
690
- }
691
- getByLabelText(enumInstance) {
692
- return screen2.getByLabelText(getEnumRatingLabel(enumInstance, this.elementSpec.instanceId));
693
- }
694
- };
695
-
696
- // src/components/CheckboxTesting.ts
697
- import wrapper10 from "@cloudscape-design/components/test-utils/dom";
698
- import { act as act9 } from "react";
699
- var CheckboxTesting = class extends AbstractComponentTesting {
700
- constructor(fieldSpec, view) {
701
- super(fieldSpec, view, (selector) => wrapper10().findCheckbox(selector));
702
- this.view = view;
703
- }
704
- click() {
705
- act9(() => {
706
- this.getElementWrapper().findNativeInput().click();
707
- });
708
- }
709
- isChecked() {
710
- return this.getElement().checked;
711
- }
712
- getElement() {
713
- const element = this.getElementWrapper().findNativeInput();
714
- return this.assertElement("None", () => element.getElement());
715
- }
716
- toggleIfNecessary(desiredCheckedState) {
717
- if (this.isChecked() !== desiredCheckedState) {
718
- this.click();
719
- }
720
- }
721
- };
722
-
723
- // src/components/HeaderTesting.ts
724
- import wrapper11 from "@cloudscape-design/components/test-utils/dom";
725
- import { expect as expect11 } from "vitest";
726
- var HeaderTesting = class extends AbstractComponentTesting {
727
- constructor(fieldSpec, view) {
728
- super(fieldSpec, view, (selector) => wrapper11().findHeader(selector));
729
- this.view = view;
730
- }
731
- expectCounterLocalisation(variables) {
732
- const localisedElements = this.view.getLocaliser().localiseField(this.elementSpec.getLocalisationKey(), variables);
733
- expect11(this.getElementWrapper().findCounter().getElement()).toHaveTextContent(localisedElements.counter);
734
- }
735
- expectCounter(counterText) {
736
- expect11(this.getElementWrapper().findCounter().getElement()).toHaveTextContent(counterText);
737
- }
738
- expectContent(content) {
739
- expect11(this.getElementWrapper().findHeadingText().getElement()).toHaveTextContent(content);
740
- }
741
- expectNotContent(content) {
742
- expect11(this.getElementWrapper().findHeadingText().getElement()).not.toHaveTextContent(content);
743
- }
744
- };
745
-
746
- // src/components/BoxTesting.ts
747
- import wrapper12 from "@cloudscape-design/components/test-utils/dom";
748
- import { expect as expect12 } from "vitest";
749
- var BoxTesting = class extends AbstractComponentTesting {
750
- constructor(fieldSpec, view) {
751
- super(fieldSpec, view, (selector) => wrapper12().findBox(selector));
752
- this.view = view;
753
- }
754
- expectContent(content) {
755
- expect12(this.getElementWrapper().getElement()).toHaveTextContent(content);
756
- }
757
- expectLocalisation(variables, alternateNs) {
758
- const localisedElements = this.view.getLocaliser().localiseField(this.elementSpec.getLocalisationKey(), variables, alternateNs);
759
- this.expectContent(localisedElements.children.trim());
760
- }
761
- };
762
-
763
- // src/components/CollectionPreferencesTesting.ts
764
- import wrapper13 from "@cloudscape-design/components/test-utils/dom";
765
- import { act as act10 } from "react";
766
- import { expect as expect13 } from "vitest";
767
- var CollectionPreferencesSetting = class {
768
- };
769
- var CollectionPreferencesTesting = class extends AbstractComponentTesting {
770
- constructor(fieldSpec, view, supportedPageSizes) {
771
- super(fieldSpec, view, (selector) => wrapper13().findCollectionPreferences(selector));
772
- this.view = view;
773
- this.supportedPageSizes = supportedPageSizes;
774
- }
775
- async expectPreferences(preferences) {
776
- const modal = this.openPreferencesModal();
777
- if (preferences.pageSize !== void 0) {
778
- const pageSizeIndex = this.getPageSizeIndex(preferences.pageSize);
779
- expect13(modal.findPageSizePreference().findOptions()[pageSizeIndex].findNativeInput().getElement()).toBeChecked();
780
- }
781
- if (preferences.stickFirstColumns !== void 0) {
782
- expect13(modal.findStickyColumnsPreference("first").findRadioGroup().findButtons()[preferences.stickFirstColumns].findNativeInput().getElement()).toBeChecked();
783
- }
784
- if (preferences.stickLastColumns !== void 0) {
785
- expect13(modal.findStickyColumnsPreference("last").findRadioGroup().findButtons()[preferences.stickLastColumns].findNativeInput().getElement()).toBeChecked();
786
- }
787
- this.expectCheckboxSetting(preferences.wrapLines, modal.findWrapLinesPreference());
788
- this.expectCheckboxSetting(preferences.stripedRows, modal.findStripedRowsPreference());
789
- this.expectCheckboxSetting(preferences.compact, modal.findContentDensityPreference());
790
- this.cancelPreferencesModal();
791
- }
792
- async editPreferences(preferences) {
793
- const modal = this.openPreferencesModal();
794
- if (preferences.pageSize !== void 0) {
795
- const pageSizeIndex = this.getPageSizeIndex(preferences.pageSize);
796
- act10(() => modal.findPageSizePreference().findOptions()[pageSizeIndex].findLabel().click());
797
- }
798
- if (preferences.stickFirstColumns !== void 0) {
799
- act10(() => modal.findStickyColumnsPreference("first").findRadioGroup().findButtons()[preferences.stickFirstColumns].findNativeInput().click());
800
- }
801
- if (preferences.stickLastColumns !== void 0) {
802
- act10(() => modal.findStickyColumnsPreference("last").findRadioGroup().findButtons()[preferences.stickLastColumns].findNativeInput().click());
803
- }
804
- this.editCheckboxSetting(preferences.wrapLines, modal.findWrapLinesPreference());
805
- this.editCheckboxSetting(preferences.stripedRows, modal.findStripedRowsPreference());
806
- this.editCheckboxSetting(preferences.compact, modal.findContentDensityPreference());
807
- this.confirmPreferencesModal();
808
- }
809
- openPreferencesModal() {
810
- act10(() => this.getElementWrapper().findTriggerButton().click());
811
- expect13(this.getElementWrapper().findModal()).not.toBeNull();
812
- return this.getElementWrapper().findModal();
813
- }
814
- confirmPreferencesModal() {
815
- act10(() => this.getElementWrapper().findModal().findConfirmButton().click());
816
- }
817
- cancelPreferencesModal() {
818
- act10(() => this.getElementWrapper().findModal().findCancelButton().click());
819
- }
820
- getPageSizeIndex(pageSize) {
821
- const pageSizeIndex = this.supportedPageSizes.indexOf(pageSize);
822
- if (pageSizeIndex === -1) {
823
- throw new Error(`Unsupported page size: ${pageSize}, only following page sizes are supported: ${JSON.stringify(this.supportedPageSizes)}.`);
824
- }
825
- return pageSizeIndex;
826
- }
827
- editCheckboxSetting(settingValue, checkbox) {
828
- if (settingValue !== void 0) {
829
- if (settingValue !== checkbox.findNativeInput().getElement().checked) {
830
- act10(() => checkbox.findNativeInput().click());
831
- }
832
- }
833
- }
834
- expectCheckboxSetting(settingValue, checkbox) {
835
- if (settingValue !== void 0) {
836
- if (settingValue) {
837
- expect13(checkbox.findNativeInput().getElement()).toBeChecked();
838
- } else {
839
- expect13(checkbox.findNativeInput().getElement()).not.toBeChecked();
840
- }
841
- }
842
- }
843
- };
844
-
845
- // src/components/LinkTesting.ts
846
- import wrapper14 from "@cloudscape-design/components/test-utils/dom";
847
- var LinkTesting = class extends AbstractComponentTesting {
848
- constructor(fieldSpec, view) {
849
- super(fieldSpec, view, (selector) => wrapper14().findLink(selector));
850
- this.view = view;
851
- }
852
- };
853
-
854
- // src/components/ToggleTesting.ts
855
- import wrapper15 from "@cloudscape-design/components/test-utils/dom";
856
- import { act as act11 } from "react";
857
- var ToggleTesting = class extends AbstractComponentTesting {
858
- constructor(fieldSpec, view) {
859
- super(fieldSpec, view, (selector) => wrapper15().findToggle(selector));
860
- this.view = view;
861
- }
862
- click() {
863
- act11(() => {
864
- this.getElementWrapper().findNativeInput().click();
865
- });
866
- }
867
- getElement() {
868
- const element = this.getElementWrapper().findNativeInput();
869
- return this.assertElement("None", () => element.getElement());
870
- }
871
- toggleIfNecessary(desiredCheckedState) {
872
- if (this.isChecked() !== desiredCheckedState) {
873
- this.click();
874
- }
875
- }
876
- isChecked() {
877
- return this.getElement().checked;
878
- }
879
- };
880
-
881
- // src/components/FlashbarTesting.ts
882
- import wrapper16 from "@cloudscape-design/components/test-utils/dom";
883
- import { waitFor as waitFor7 } from "@testing-library/react";
884
- import { expect as expect14 } from "vitest";
885
- var FlashbarTesting = class extends AbstractComponentTesting {
886
- constructor(fieldSpec, view) {
887
- super(fieldSpec, view, (selector) => wrapper16().findFlashbar(selector));
888
- this.view = view;
889
- }
890
- async awaitMessages() {
891
- await waitFor7(() => expect14(this.getElementWrapper().findItems().length).toBeGreaterThan(0));
892
- const wrappers = this.getElementWrapper().findItems();
893
- for (let index = 0; index < wrappers.length; index++) {
894
- const wrapper29 = wrappers[index];
895
- await waitFor7(() => expect14(wrapper29.findContent()).not.toBeNull());
896
- }
897
- }
898
- expectMessagePresentCount(text, count, headerMessage) {
899
- if (this.queryElement() === null) {
900
- expect14(0).toBe(count);
901
- } else {
902
- const wrappers = this.getElementWrapper().findItems();
903
- const textContent = wrappers.map((flash) => {
904
- const element = headerMessage ? flash.findHeader().getElement() : flash.findContent().getElement();
905
- return element.textContent;
906
- });
907
- let actualCount = 0;
908
- if (typeof text === "string") {
909
- actualCount = textContent.filter((txt) => txt === text).length;
910
- } else {
911
- actualCount = textContent.filter((txt) => text.test(txt)).length;
912
- }
913
- expect14(actualCount).toBe(count);
914
- }
915
- }
916
- expectMessagePresentOnce(text, headerMessage) {
917
- this.expectMessagePresentCount(text, 1, headerMessage);
918
- }
919
- expectMessageNotPresent(text, headerMessage) {
920
- this.expectMessagePresentCount(text, 0, headerMessage);
921
- }
922
- };
923
-
924
- // src/components/SegmentedControlTesting.ts
925
- import wrapper17 from "@cloudscape-design/components/test-utils/dom";
926
- import { waitFor as waitFor8 } from "@testing-library/react";
927
- import { act as act12 } from "react";
928
- import { expect as expect15 } from "vitest";
929
- var SegmentedControlTesting = class extends AbstractComponentTesting {
930
- constructor(fieldSpec, view, factory) {
931
- super(fieldSpec, view, (selector) => wrapper17().findSegmentedControl(selector));
932
- this.view = view;
933
- this.factory = factory;
934
- }
935
- async selectEnum(enumValue) {
936
- await this.select(this.factory.values.findIndex((value) => value === enumValue));
937
- }
938
- async select(index) {
939
- act12(() => {
940
- this.getElementWrapper().findSegments()[index].click();
941
- });
942
- await waitFor8(() => expect15(this.getElementWrapper().findSelectedSegment().getElement()).toStrictEqual(this.getElementWrapper().findSegments()[index].getElement()));
943
- }
944
- expectSelected(index) {
945
- const selectedElement = this.getElementWrapper().findSelectedSegment();
946
- if (selectedElement === null || selectedElement === void 0) {
947
- throw new Error(this.elementNotFoundErrorMessage(this.elementSpec.getDataTestId()));
948
- }
949
- const expectedElement = this.getElementWrapper().findSegments()[index];
950
- expect15(selectedElement).toStrictEqual(expectedElement);
951
- }
952
- expectSelectedEnum(enumValue) {
953
- this.expectSelected(this.factory.values.findIndex((value) => value === enumValue));
954
- }
955
- getSelectedEnum() {
956
- const selectedElement = this.getElementWrapper().findSelectedSegment();
957
- if (selectedElement === null || selectedElement === void 0) {
958
- throw new Error(this.elementNotFoundErrorMessage(this.elementSpec.getDataTestId()));
959
- }
960
- const textContent = selectedElement.getElement().textContent;
961
- const allLabels = this.view.getLocaliser().getAllEnumLabels(this.factory);
962
- const index = allLabels.findIndex((label) => label === textContent);
963
- return this.factory.values[index];
964
- }
965
- };
966
-
967
- // src/components/AlertTesting.ts
968
- import wrapper18 from "@cloudscape-design/components/test-utils/dom";
969
- import { expect as expect16 } from "vitest";
970
- var AlertTesting = class extends AbstractComponentTesting {
971
- constructor(fieldSpec, view) {
972
- super(fieldSpec, view, (selector) => wrapper18().findAlert(selector));
973
- this.view = view;
974
- }
975
- expectContent(content) {
976
- expect16(this.getElementWrapper().findContent().getElement()).toHaveTextContent(content);
977
- }
978
- expectLocalisation(variables, alternateNs) {
979
- const localisedElements = this.view.getLocaliser().localiseField(this.elementSpec.getLocalisationKey(), variables, alternateNs);
980
- this.expectContent(localisedElements.children);
981
- }
982
- };
983
-
984
- // src/components/StatusIndicatorTesting.ts
985
- import wrapper19 from "@cloudscape-design/components/test-utils/dom";
986
- import { expect as expect17 } from "vitest";
987
- var StatusIndicatorTesting = class extends AbstractComponentTesting {
988
- constructor(fieldSpec, view) {
989
- super(fieldSpec, view, (selector) => wrapper19().findStatusIndicator(selector));
990
- this.view = view;
991
- }
992
- expectContent(content) {
993
- expect17(this.getElementWrapper().getElement()).toHaveTextContent(content);
994
- }
995
- };
996
-
997
- // src/components/CardsTesting.ts
998
- import wrapper20 from "@cloudscape-design/components/test-utils/dom";
999
- import { waitFor as waitFor9 } from "@testing-library/react";
1000
- import { act as act13 } from "react";
1001
- import { expect as expect18 } from "vitest";
1002
- var CardsTesting = class extends AbstractComponentTesting {
1003
- constructor(fieldSpec, view) {
1004
- super(fieldSpec, view, (selector) => wrapper20().findCards(selector));
1005
- this.view = view;
1006
- }
1007
- expectSelectedItems(selectedItemIndices) {
1008
- const allItems = this.getElementWrapper().findItems();
1009
- const selectedItems = this.getElementWrapper().findSelectedItems();
1010
- for (let index = 0; index < allItems.length; index++) {
1011
- if (selectedItemIndices.indexOf(index) !== -1) {
1012
- const item = allItems[index];
1013
- expect18(selectedItems).toContainEqual(item);
1014
- }
1015
- }
1016
- }
1017
- expectUnselectedItems(unselectedItemIndices) {
1018
- const allItems = this.getElementWrapper().findItems();
1019
- const selectedItems = this.getElementWrapper().findSelectedItems();
1020
- for (let index = 0; index < allItems.length; index++) {
1021
- if (unselectedItemIndices.indexOf(index) !== -1) {
1022
- const item = allItems[index];
1023
- expect18(selectedItems).not.toContain(item);
1024
- }
1025
- }
1026
- this.getElementWrapper().findLoadingText();
1027
- }
1028
- async awaitLoadingText(expectedText) {
1029
- await waitFor9(() => expect18(this.getElementWrapper().findLoadingText().getElement()).toHaveTextContent(expectedText));
1030
- return waitFor9(() => expect18(this.getElementWrapper().findLoadingText()).toBeNull());
1031
- }
1032
- clickItems(clickedItemIndices) {
1033
- const allItems = this.getElementWrapper().findItems();
1034
- for (let index = 0; index < allItems.length; index++) {
1035
- if (clickedItemIndices.indexOf(index) !== -1) {
1036
- const item = allItems[index];
1037
- const selectionArea = this.assertElement("none", () => item.findSelectionArea());
1038
- act13(() => {
1039
- selectionArea.click();
1040
- });
1041
- }
1042
- }
1043
- }
1044
- expectCardTitle(cardIndex, expectedTitle) {
1045
- expect18(this.getElementWrapper().findItems()[cardIndex].findCardHeader().getElement()).toHaveTextContent(expectedTitle);
1046
- }
1047
- getItemCount() {
1048
- return this.getElementWrapper().findItems().length;
1049
- }
1050
- async awaitLoading() {
1051
- await waitFor9(() => expect18(this.getElementWrapper().findLoadingText()).not.toBeNull());
1052
- }
1053
- async awaitNotLoading() {
1054
- await waitFor9(() => expect18(this.getElementWrapper().findLoadingText()).toBeNull());
1055
- }
1056
- };
1057
-
1058
- // src/components/TextareaTesting.ts
1059
- import wrapper21 from "@cloudscape-design/components/test-utils/dom";
1060
- import { act as act14 } from "react";
1061
- import { expect as expect19 } from "vitest";
1062
- var TextareaTesting = class extends AbstractInputTesting {
1063
- constructor(fieldSpec, view) {
1064
- super(fieldSpec, view, (selector) => wrapper21().findTextarea(selector));
1065
- this.view = view;
1066
- }
1067
- setStringValue(value) {
1068
- act14(() => {
1069
- this.getElementWrapper().setTextareaValue(value);
1070
- });
1071
- }
1072
- expectValue(value) {
1073
- expect19(this.getNativeHTMLInput()).toHaveValue(value === void 0 ? "" : value);
1074
- }
1075
- getNativeHTMLInput() {
1076
- return this.getElementWrapper().findNativeTextarea().getElement();
1077
- }
1078
- };
1079
-
1080
- // src/components/TabsTesting.ts
1081
- import wrapper22 from "@cloudscape-design/components/test-utils/dom";
1082
- import { act as act15 } from "react";
1083
- import { expect as expect20 } from "vitest";
1084
- var TabsTesting = class extends AbstractComponentTesting {
1085
- constructor(fieldSpec, view) {
1086
- super(fieldSpec, view, (selector) => wrapper22().findTabs(selector));
1087
- this.view = view;
1088
- }
1089
- expectActiveTab(index) {
1090
- const activeTab = this.getElementWrapper().findActiveTab();
1091
- this.assertTabAtIndex(activeTab, index);
1092
- const tabLinkByIndex = this.getElementWrapper().findTabLinkByIndex(index + 1);
1093
- this.assertTabAtIndex(tabLinkByIndex, index);
1094
- expect20(activeTab).toEqual(tabLinkByIndex);
1095
- }
1096
- selectTab(index) {
1097
- const tabLinkByIndex = this.getElementWrapper().findTabLinkByIndex(index + 1);
1098
- this.assertTabAtIndex(tabLinkByIndex, index);
1099
- act15(() => {
1100
- tabLinkByIndex.click();
1101
- });
1102
- }
1103
- assertTabAtIndex(tab, index) {
1104
- if (tab === null || tab === void 0) {
1105
- throw new Error(this.elementNotFoundErrorMessage("No tab at index = " + index.toString()));
1106
- }
1107
- }
1108
- };
1109
-
1110
- // src/components/TextFilterTesting.ts
1111
- import wrapper23 from "@cloudscape-design/components/test-utils/dom";
1112
- var TextFilterTesting = class extends AbstractComponentTesting {
1113
- constructor(fieldSpec, view) {
1114
- super(fieldSpec, view, (selector) => wrapper23().findTextFilter(selector));
1115
- this.view = view;
1116
- }
1117
- };
1118
-
1119
- // src/components/TextContentTesting.ts
1120
- import wrapper24 from "@cloudscape-design/components/test-utils/dom";
1121
- import { expect as expect21 } from "vitest";
1122
- var TextContentTesting = class extends AbstractComponentTesting {
1123
- constructor(fieldSpec, view) {
1124
- super(fieldSpec, view, (selector) => wrapper24().findTextContent(selector));
1125
- this.view = view;
1126
- }
1127
- expectContent(content) {
1128
- expect21(this.getElementWrapper().getElement()).toHaveTextContent(content);
1129
- }
1130
- };
1131
-
1132
- // src/components/PaginationTesting.ts
1133
- import wrapper25 from "@cloudscape-design/components/test-utils/dom";
1134
- import { act as act16 } from "react";
1135
- import { expect as expect22 } from "vitest";
1136
- var PaginationTesting = class extends AbstractComponentTesting {
1137
- constructor(fieldSpec, view) {
1138
- super(fieldSpec, view, (selector) => wrapper25().findPagination(selector));
1139
- this.view = view;
1140
- }
1141
- expectPageParams(currentPageDisplayIndex, pageCount) {
1142
- const pageNumbers = this.getElementWrapper().findPageNumbers();
1143
- const lastPage = pageNumbers[pageNumbers.length - 1];
1144
- expect22(lastPage.getElement()).toHaveTextContent(pageCount.toString());
1145
- expect22(this.getElementWrapper().findCurrentPage().getElement()).toHaveTextContent(currentPageDisplayIndex);
1146
- }
1147
- async changePage(fromIndex, toIndex) {
1148
- const nextButton = this.getElementWrapper().findNextPageButton();
1149
- const prevButton = this.getElementWrapper().findPreviousPageButton();
1150
- if (toIndex === fromIndex + 1) {
1151
- act16(() => nextButton.click());
1152
- } else if (toIndex === fromIndex - 1) {
1153
- act16(() => prevButton.click());
1154
- } else {
1155
- const pageIndexTo = (toIndex + 1).toString();
1156
- const pageNumbersWithIndex = this.getElementWrapper().findPageNumbers().filter((pageNumber) => pageNumber.getElement().textContent === pageIndexTo);
1157
- if (pageNumbersWithIndex.length !== 1) {
1158
- throw new Error(`Expected page index ${pageIndexTo} not displayed currently in pagination component! Here are the currently displayed page numbers: ${this.getElementWrapper().findPageNumbers().map((n) => n.getElement().textContent)}`);
1159
- }
1160
- act16(() => pageNumbersWithIndex[0].click());
1161
- }
1162
- }
1163
- };
1164
-
1165
- // src/components/FormTesting.ts
1166
- import wrapper26 from "@cloudscape-design/components/test-utils/dom";
1167
- var FormTesting = class extends AbstractComponentTesting {
1168
- constructor(fieldSpec, view) {
1169
- super(fieldSpec, view, (selector) => wrapper26().findForm(selector));
1170
- this.view = view;
1171
- }
1172
- };
1173
-
1174
- // src/components/ProgressBarTesting.ts
1175
- import wrapper27 from "@cloudscape-design/components/test-utils/dom";
1176
- import { waitFor as waitFor10 } from "@testing-library/react";
1177
- import { expect as expect23 } from "vitest";
1178
- var ProgressBarTesting = class extends AbstractComponentTesting {
1179
- constructor(fieldSpec, view) {
1180
- super(fieldSpec, view, (selector) => wrapper27().findProgressBar(selector));
1181
- this.view = view;
1182
- }
1183
- async awaitPercentageDisplay(text) {
1184
- await waitFor10(() => expect23(this.getElementWrapper().findPercentageText()).not.toBeNull());
1185
- const percentageText = this.getElementWrapper().findPercentageText();
1186
- await waitFor10(() => expect23(percentageText.findTextContent()).not.toBeNull());
1187
- await waitFor10(() => expect23(percentageText.findTextContent().getElement()).toHaveTextContent(text.toString()));
1188
- }
1189
- async awaitResultText(text) {
1190
- await waitFor10(() => expect23(this.getElementWrapper().findResultText().findTextContent().getElement()).toHaveTextContent(text));
1191
- }
1192
- };
1193
-
1194
- // src/components/IconTesting.ts
1195
- import wrapper28 from "@cloudscape-design/components/test-utils/dom";
1196
- var IconTesting = class extends AbstractComponentTesting {
1197
- constructor(fieldSpec, view) {
1198
- super(fieldSpec, view, (selector) => wrapper28().findIcon(selector));
1199
- this.view = view;
1200
- }
1201
- };
1202
-
1203
- // src/components/TestingFactory.ts
1204
- var TestingFactory = class {
1205
- constructor(parentView) {
1206
- this.parentView = parentView;
1207
- }
1208
- multiselect(fieldSpec, expandToViewport) {
1209
- return new MultiselectTesting(fieldSpec, this.parentView, expandToViewport);
1210
- }
1211
- select(fieldSpec, expandToViewport) {
1212
- return new SelectTesting(fieldSpec, this.parentView, expandToViewport);
1213
- }
1214
- stringInput(fieldSpec) {
1215
- return new StringInputTesting(fieldSpec, this.parentView);
1216
- }
1217
- numberInput(fieldSpec) {
1218
- return new NumberInputTesting(fieldSpec, this.parentView);
1219
- }
1220
- table(fieldSpec) {
1221
- return new TableTesting(fieldSpec, this.parentView);
1222
- }
1223
- wizard(fieldSpec) {
1224
- return new WizardTesting(fieldSpec, this.parentView);
1225
- }
1226
- datePicker(fieldSpec) {
1227
- return new DatePickerTesting(fieldSpec, this.parentView);
1228
- }
1229
- button(fieldSpec) {
1230
- return new ButtonTesting(fieldSpec, this.parentView);
1231
- }
1232
- buttonDropdown(fieldSpec) {
1233
- return new ButtonDropdownTesting(fieldSpec, this.parentView);
1234
- }
1235
- modal(viewSpec) {
1236
- return new ModalTesting(viewSpec, this.parentView);
1237
- }
1238
- rating(viewSpec, factory, toOrderNumber) {
1239
- return new RatingTesting(viewSpec, this.parentView, factory, toOrderNumber);
1240
- }
1241
- checkbox(fieldSpec) {
1242
- return new CheckboxTesting(fieldSpec, this.parentView);
1243
- }
1244
- header(fieldSpec) {
1245
- return new HeaderTesting(fieldSpec, this.parentView);
1246
- }
1247
- box(fieldSpec) {
1248
- return new BoxTesting(fieldSpec, this.parentView);
1249
- }
1250
- collectionPreferences(fieldSpec, pageSizes) {
1251
- return new CollectionPreferencesTesting(fieldSpec, this.parentView, pageSizes);
1252
- }
1253
- link(fieldSpec) {
1254
- return new LinkTesting(fieldSpec, this.parentView);
1255
- }
1256
- toggle(fieldSpec) {
1257
- return new ToggleTesting(fieldSpec, this.parentView);
1258
- }
1259
- flashbar(fieldSpec) {
1260
- return new FlashbarTesting(fieldSpec, this.parentView);
1261
- }
1262
- segmentedControl(fieldSpec, factory) {
1263
- return new SegmentedControlTesting(fieldSpec, this.parentView, factory);
1264
- }
1265
- alert(fieldSpec) {
1266
- return new AlertTesting(fieldSpec, this.parentView);
1267
- }
1268
- statusIndicator(fieldSpec) {
1269
- return new StatusIndicatorTesting(fieldSpec, this.parentView);
1270
- }
1271
- cards(fieldSpec) {
1272
- return new CardsTesting(fieldSpec, this.parentView);
1273
- }
1274
- textarea(fieldSpec) {
1275
- return new TextareaTesting(fieldSpec, this.parentView);
1276
- }
1277
- tabs(fieldSpec) {
1278
- return new TabsTesting(fieldSpec, this.parentView);
1279
- }
1280
- textFilter(fieldSpec) {
1281
- return new TextFilterTesting(fieldSpec, this.parentView);
1282
- }
1283
- textContent(fieldSpec) {
1284
- return new TextContentTesting(fieldSpec, this.parentView);
1285
- }
1286
- pageSelect(fieldSpec) {
1287
- return new PaginationTesting(fieldSpec, this.parentView);
1288
- }
1289
- form(elementSpec) {
1290
- return new FormTesting(elementSpec, this.parentView);
1291
- }
1292
- progressBar(fieldSpec) {
1293
- return new ProgressBarTesting(fieldSpec, this.parentView);
1294
- }
1295
- icon(fieldSpec) {
1296
- return new IconTesting(fieldSpec, this.parentView);
1297
- }
1298
- };
1299
-
1300
- // src/views/AbstractViewTesting.tsx
1301
- import { prettyDOM, screen as screen3 } from "@testing-library/react";
1302
- import { writeFileSync } from "fs";
1303
- import userEvent from "@testing-library/user-event";
1304
- import { expect as expect24 } from "vitest";
1305
- var AbstractViewTesting = class {
1306
- constructor(namespace, viewSpec, testLocalisation) {
1307
- this.namespace = namespace;
1308
- this.viewSpec = viewSpec;
1309
- this.testLocalisation = testLocalisation;
1310
- this.factory = new TestingFactory(this);
1311
- this.parent = viewSpec.parent;
1312
- }
1313
- getLocaliser() {
1314
- return this.testLocalisation.getLocaliser(this.namespace);
1315
- }
1316
- fromSpec(componentSpec, testElements) {
1317
- return ViewSpec.create(componentSpec.key, componentSpec.ns, (spec) => testElements(componentSpec.elements, this.factory));
1318
- }
1319
- printDOM() {
1320
- const dom = prettyDOM(void 0, 1e7, { highlight: false });
1321
- if (dom) {
1322
- writeFileSync("./DOM.txt", dom.toString());
1323
- }
1324
- }
1325
- /**
1326
- * renders the component
1327
- */
1328
- renderComponent() {
1329
- }
1330
- async waitForView(viewSpec) {
1331
- await this.factory.form(viewSpec).awaitPresent();
1332
- }
1333
- expectViewNotPresent(viewSpec) {
1334
- expect24(screen3.queryByTestId(viewSpec.getDataTestId())).not.toBeInTheDocument();
1335
- }
1336
- translate(key, variables, alternateNs) {
1337
- return this.getLocaliser().localiseKey(key, variables, alternateNs);
1338
- }
1339
- /**
1340
- * To test triggering the default action, e.g. form submit, by pressing enter.
1341
- */
1342
- async pressEnter(element) {
1343
- await userEvent.type(element, "{enter}");
1344
- }
1345
- };
1346
-
1347
- // src/views/CSVNoItemsViewTesting.tsx
1348
- import { CSV_NO_ITEMS_VIEW_SPEC } from "@ebertjendustries/cswrapper";
1349
- var CSVNoItemsViewTesting = class extends AbstractViewTesting {
1350
- constructor(namespace, viewSpec, entityTypeFactory, testLocalisation) {
1351
- super(namespace, viewSpec, testLocalisation);
1352
- this.entityTypeFactory = entityTypeFactory;
1353
- this.noItemsView = this.fromSpec(CSV_NO_ITEMS_VIEW_SPEC(this.namespace), (elements, factory) => ({
1354
- boxHeading: factory.box(elements.boxHeading),
1355
- boxBody: factory.box(elements.boxBody)
1356
- }));
1357
- }
1358
- async awaitPresent() {
1359
- await this.waitForView(CSV_NO_ITEMS_VIEW_SPEC(this.namespace));
1360
- this.expectPresent();
1361
- }
1362
- async awaitNotPresent() {
1363
- await this.noItemsView.elements.boxHeading.awaitNotPresent();
1364
- }
1365
- expectPresent() {
1366
- this.noItemsView.elements.boxHeading.expectPresent();
1367
- }
1368
- expectNotPresent() {
1369
- this.noItemsView.elements.boxHeading.expectNotPresent();
1370
- }
1371
- expectLocalisation(itemType) {
1372
- this.noItemsView.elements.boxBody.expectLocalisation({ itemType: this.getLocaliser().getEnumLabel(this.entityTypeFactory, itemType) });
1373
- }
1374
- };
1375
-
1376
- // src/views/CSVPriceInputViewTesting.tsx
1377
- import { CSV_PRICE_INPUT_VIEW_SPEC } from "@ebertjendustries/cswrapper";
1378
- import { PriceUtils } from "@ebertjendustries/cswrapper";
1379
- var CSVPriceInputViewTesting = class extends AbstractViewTesting {
1380
- constructor(namespace, viewSpec, testLocalisation, currencyFactory, expandToViewport) {
1381
- super(namespace, viewSpec, testLocalisation);
1382
- this.currencyFactory = currencyFactory;
1383
- this.expandToViewport = expandToViewport;
1384
- this.csvPriceInputView = this.fromSpec(CSV_PRICE_INPUT_VIEW_SPEC(this.parent, this.viewSpec.key), (elements, factory) => ({
1385
- amountInput: factory.numberInput(elements.inputPrice),
1386
- currencyInput: factory.select(elements.selectCurrency, this.expandToViewport),
1387
- displayBox: factory.box(elements.boxPriceDisplay)
1388
- }));
1389
- }
1390
- expectDisplayPrice(price) {
1391
- this.csvPriceInputView.elements.displayBox.expectContent(PriceUtils.getFormattedPrice("en", price));
1392
- }
1393
- async setPrice(price) {
1394
- if (isNaN(price.priceInCents)) {
1395
- this.csvPriceInputView.elements.amountInput.clear();
1396
- } else {
1397
- const priceX = price.priceInCents / 100;
1398
- this.csvPriceInputView.elements.amountInput.setStringValue(priceX.toString());
1399
- }
1400
- await this.csvPriceInputView.elements.currencyInput.selectOrDeselect([this.currencyFactory.getEnumIndex(price.currency)]);
1401
- }
1402
- async expectPrice(price) {
1403
- if (isNaN(price.priceInCents)) {
1404
- this.csvPriceInputView.elements.amountInput.expectEmpty();
1405
- } else {
1406
- const priceX = price.priceInCents / 100;
1407
- this.csvPriceInputView.elements.amountInput.expectValue(priceX);
1408
- }
1409
- await this.csvPriceInputView.elements.currencyInput.expectEnumEntries(this.currencyFactory, [price.currency]);
1410
- }
1411
- };
1412
-
1413
- // src/views/CSVSearchFilterViewTesting.tsx
1414
- import { CSV_SEARCH_FILTER_VIEW_SPEC } from "@ebertjendustries/cswrapper";
1415
- var CSVSearchFilterViewTesting = class extends AbstractViewTesting {
1416
- constructor(namespace, viewSpec, testLocalisation) {
1417
- super(namespace, viewSpec, testLocalisation);
1418
- this.csvSearchFilterView = this.fromSpec(CSV_SEARCH_FILTER_VIEW_SPEC(this.parent, this.viewSpec.key), (elements, factory) => ({
1419
- searchTextFilter: factory.stringInput(elements.inputSearch),
1420
- searchButton: factory.button(elements.buttonSearch)
1421
- }));
1422
- }
1423
- async awaitNotLoading() {
1424
- await this.csvSearchFilterView.elements.searchButton.awaitNotLoading();
1425
- }
1426
- searchFor(searchText) {
1427
- this.csvSearchFilterView.elements.searchTextFilter.overwriteAndVerify(searchText);
1428
- this.search();
1429
- }
1430
- search() {
1431
- this.csvSearchFilterView.elements.searchButton.click();
1432
- }
1433
- editSearchText(searchText) {
1434
- this.csvSearchFilterView.elements.searchTextFilter.setStringValue(searchText);
1435
- }
1436
- expectState(expectedSearchText, disabledButton) {
1437
- this.csvSearchFilterView.elements.searchTextFilter.expectValue(expectedSearchText);
1438
- if (disabledButton) {
1439
- this.csvSearchFilterView.elements.searchButton.expectDisabled();
1440
- } else {
1441
- this.csvSearchFilterView.elements.searchButton.expectEnabled();
1442
- }
1443
- }
1444
- expectFilteringEnabled() {
1445
- this.csvSearchFilterView.elements.searchButton.expectEnabled();
1446
- }
1447
- expectFilteringDisabled() {
1448
- this.csvSearchFilterView.elements.searchButton.expectDisabled();
1449
- }
1450
- };
1451
-
1452
- // src/views/CSVTextPromptModalViewTesting.tsx
1453
- import {
1454
- CSV_TEXT_PROMPT_MODAL_VIEW_SPEC
1455
- } from "@ebertjendustries/cswrapper";
1456
- var CSVTextPromptModalViewTesting = class extends AbstractViewTesting {
1457
- constructor(namespace, viewSpec, testLocalisation) {
1458
- super(namespace, viewSpec, testLocalisation);
1459
- this.csvTextPromptModalView = this.fromSpec(CSV_TEXT_PROMPT_MODAL_VIEW_SPEC(this.parent, this.viewSpec.key), (elements, factory) => ({
1460
- headerHeading: factory.header(elements.headerHeading),
1461
- boxBodyText: factory.box(elements.boxBodyText),
1462
- buttonPrimary: factory.button(elements.buttonPrimary),
1463
- buttonSecondary: factory.button(elements.buttonSecondary),
1464
- modal: factory.modal(this.viewSpec)
1465
- }));
1466
- }
1467
- expectHidden() {
1468
- this.csvTextPromptModalView.elements.modal.expectHidden();
1469
- }
1470
- expectVisible() {
1471
- this.csvTextPromptModalView.elements.modal.expectVisible();
1472
- }
1473
- async awaitVisible() {
1474
- return this.csvTextPromptModalView.elements.modal.awaitVisible();
1475
- }
1476
- async awaitHidden() {
1477
- return this.csvTextPromptModalView.elements.modal.awaitHidden();
1478
- }
1479
- dismiss() {
1480
- this.csvTextPromptModalView.elements.modal.dismiss();
1481
- }
1482
- confirm() {
1483
- this.csvTextPromptModalView.elements.buttonPrimary.click();
1484
- }
1485
- async expectVisibleAfterOpsThenConfirm(operations, navigatingAway) {
1486
- for (let index = 0; index < operations.length; index++) {
1487
- const operation = operations[index];
1488
- this.expectHidden();
1489
- operation();
1490
- await this.awaitVisible();
1491
- this.confirm();
1492
- if (!navigatingAway) {
1493
- await this.awaitHidden();
1494
- }
1495
- }
1496
- }
1497
- async expectVisibleAfterOpsThenDismiss(operations, navigatingAway) {
1498
- for (let index = 0; index < operations.length; index++) {
1499
- const operation = operations[index];
1500
- this.expectHidden();
1501
- operation();
1502
- await this.awaitVisible();
1503
- this.dismiss();
1504
- if (!navigatingAway) {
1505
- await this.awaitHidden();
1506
- }
1507
- }
1508
- }
1509
- };
1510
-
1511
- // src/mocks/MockBrowserAPIs.ts
1512
- import { vi } from "vitest";
1513
- var realDateNow = global.Date.now;
1514
- var MockBrowserAPIs = class {
1515
- static mockConfirmAlways(confirm) {
1516
- return window.confirm = vi.fn().mockImplementation(() => confirm);
1517
- }
1518
- static mockScroll() {
1519
- return window.scrollTo = vi.fn();
1520
- }
1521
- static mockDateNow(epochMillisToReturn) {
1522
- realDateNow = Date.now.bind(global.Date);
1523
- const dateNowStub = vi.fn(() => epochMillisToReturn);
1524
- global.Date.now = dateNowStub;
1525
- return dateNowStub;
1526
- }
1527
- static resetDateNow() {
1528
- global.Date.now = realDateNow;
1529
- }
1530
- };
1531
-
1532
- // src/mocks/MockRestClient.ts
1533
- import { vi as vi2 } from "vitest";
1534
- import { assert } from "console";
1535
- import { Log } from "@ebertjendustries/cswrapper";
1536
- import { sleep } from "@ebertjendustries/cswrapper";
1537
- import * as RealRestClient from "@ebertjendustries/cswrapper";
1538
- import { isContentWithMessages } from "@ebertjendustries/cswrapper";
1539
- var LOGGER = new Log("RestClientMock");
1540
- var MockResponseStore = class {
1541
- constructor(parentUUID) {
1542
- this.parentUUID = parentUUID;
1543
- this.responses = {};
1544
- this.nextResponseIndex = {};
1545
- this.simulatedDelaysInSeconds = {};
1546
- }
1547
- addResponse(url, response, delayInMilliseconds) {
1548
- if (this.responses.hasOwnProperty(url)) {
1549
- this.responses[url].push(response);
1550
- this.simulatedDelaysInSeconds[url].push(delayInMilliseconds);
1551
- } else {
1552
- this.responses[url] = [response];
1553
- this.nextResponseIndex[url] = 0;
1554
- this.simulatedDelaysInSeconds[url] = [delayInMilliseconds];
1555
- }
1556
- }
1557
- consumeNextResponse(url) {
1558
- if (this.responses.hasOwnProperty(url)) {
1559
- const responses = this.responses[url];
1560
- const nextResponseIndex = this.nextResponseIndex[url];
1561
- if (nextResponseIndex === responses.length) {
1562
- throw new Error(`${this.parentUUID} Unexpected next call to url ${url}. Already consumed ${responses.length} call response(s). Please check your logic, maybe your prod code behaves in unexpected ways, or you forgot to add the mock response value.`);
1563
- }
1564
- const response = this.responses[url][nextResponseIndex];
1565
- this.nextResponseIndex[url] = this.nextResponseIndex[url] + 1;
1566
- return { response, delay: this.simulatedDelaysInSeconds[url][nextResponseIndex] };
1567
- } else {
1568
- throw new Error(`${this.parentUUID} No mock configured for url ${url}. Known urls are: ${Object.keys(this.responses)}.`);
1569
- }
1570
- }
1571
- expectAllCalled(hard) {
1572
- Object.keys(this.nextResponseIndex).forEach((url) => {
1573
- const expectedCondition = this.nextResponseIndex[url] === this.responses[url].length;
1574
- if (hard && !expectedCondition) {
1575
- throw new Error(`${this.parentUUID} For url ${url}, not every expected call has been consumed. Consumed ${this.nextResponseIndex[url]} calls, but expected ${this.responses[url].length} calls.`);
1576
- } else {
1577
- assert(expectedCondition, `${this.parentUUID} For url ${url}, not every expected call has been consumed. Consumed ${this.nextResponseIndex[url]} calls, but expected ${this.responses[url].length} calls.`);
1578
- }
1579
- });
1580
- }
1581
- };
1582
- function setupRestClientMock(controllerSpec) {
1583
- const mockRestClient = new MockRestClient(controllerSpec.key);
1584
- const mock = vi2.spyOn(RealRestClient, "createRestClient");
1585
- LOGGER.info(`Setting up mock rest client with key ${controllerSpec.key}.`);
1586
- mock.mockImplementation(() => {
1587
- return mockRestClient;
1588
- });
1589
- return mockRestClient;
1590
- }
1591
- var MockRestClient = class {
1592
- constructor(name) {
1593
- this.get = vi2.fn();
1594
- this.put = vi2.fn();
1595
- this.post = vi2.fn();
1596
- this.del = vi2.fn();
1597
- this.uuid = "<" + crypto.randomUUID().split("-")[4] + ">";
1598
- LOGGER.info(`Instantiating mock rest client with name ${name} and UUID ${this.uuid}.`);
1599
- this.getResponseValues = new MockResponseStore(this.uuid);
1600
- this.putResponseValues = new MockResponseStore(this.uuid);
1601
- this.postResponseValues = new MockResponseStore(this.uuid);
1602
- this.deleteResponseValues = new MockResponseStore(this.uuid);
1603
- this.mockGet();
1604
- this.mockPut();
1605
- this.mockPost();
1606
- this.mockDelete();
1607
- }
1608
- expectAllHaveBeenCalled(hard) {
1609
- this.getResponseValues.expectAllCalled(hard);
1610
- this.putResponseValues.expectAllCalled(hard);
1611
- this.postResponseValues.expectAllCalled(hard);
1612
- this.deleteResponseValues.expectAllCalled(hard);
1613
- }
1614
- addGetResponse(url, response, delayInMilliseconds) {
1615
- LOGGER.info(`${this.uuid} Configuring GET ${url} ${this.getDelayForLogging(delayInMilliseconds)}.`);
1616
- this.getResponseValues.addResponse(url, response, delayInMilliseconds);
1617
- }
1618
- addPutResponse(url, response, delayInMilliseconds) {
1619
- LOGGER.info(`${this.uuid} Configuring PUT ${url} ${this.getDelayForLogging(delayInMilliseconds)}.`);
1620
- this.putResponseValues.addResponse(url, response, delayInMilliseconds);
1621
- }
1622
- addPostResponse(url, response, delayInMilliseconds) {
1623
- LOGGER.info(`${this.uuid} Configuring POST ${url} ${this.getDelayForLogging(delayInMilliseconds)}.`);
1624
- this.postResponseValues.addResponse(url, response, delayInMilliseconds);
1625
- }
1626
- addDeleteResponse(url, response, delayInMilliseconds) {
1627
- LOGGER.info(`${this.uuid} Configuring DELETE ${url} ${this.getDelayForLogging(delayInMilliseconds)}.`);
1628
- this.deleteResponseValues.addResponse(url, response, delayInMilliseconds);
1629
- }
1630
- getDelayForLogging(delayInMilliseconds) {
1631
- return delayInMilliseconds === void 0 ? "- no delay" : `- ${delayInMilliseconds} ms`;
1632
- }
1633
- mockGet() {
1634
- this.doMocking(this.get, this.getResponseValues);
1635
- }
1636
- mockPut() {
1637
- this.doMocking(this.put, this.putResponseValues);
1638
- }
1639
- mockPost() {
1640
- this.doMocking(this.post, this.postResponseValues);
1641
- }
1642
- mockDelete() {
1643
- this.doMocking(this.del, this.deleteResponseValues);
1644
- }
1645
- doMocking(mock, mockResponseStore) {
1646
- mock.mockImplementation(
1647
- async (endpoint, payload, operation, header) => {
1648
- const val = mockResponseStore.consumeNextResponse(endpoint);
1649
- const response = val.response;
1650
- const delayInMilliseconds = val.delay;
1651
- if (delayInMilliseconds !== void 0) {
1652
- await sleep(delayInMilliseconds);
1653
- }
1654
- if (response !== null && response !== void 0 && isContentWithMessages(response)) {
1655
- return Promise.reject(response);
1656
- }
1657
- return this.mockImpl(response, endpoint, payload, operation, header);
1658
- }
1659
- );
1660
- }
1661
- mockImpl(returnValue, endpoint, payload, operation, header) {
1662
- LOGGER.debug(`${this.uuid} -----------> Mock REST API call <---------------`);
1663
- LOGGER.debug(`${this.uuid} Calling REST API endpoint ${endpoint} with operation ${operation} and header <${header}>`);
1664
- const returnPromise = Promise.resolve({ content: returnValue, messages: [] });
1665
- LOGGER.debug(`${this.uuid} DONE calling REST API endpoint ${endpoint} with operation ${operation} and header ${header}`);
1666
- return returnPromise;
1667
- }
1668
- };
1669
-
1670
- // src/mocks/MockServerBuilder.ts
1671
- var MockServerBuilder = class _MockServerBuilder {
1672
- constructor(port, requireFunc) {
1673
- this.port = port;
1674
- this.mockData = {};
1675
- this.redirectUrls = {};
1676
- this.jsonServer = requireFunc("json-server");
1677
- this.server = this.jsonServer.create();
1678
- this.server.use(this.jsonServer.bodyParser);
1679
- }
1680
- addToMockData(key, data) {
1681
- this.mockData[key] = data;
1682
- }
1683
- /**
1684
- * Puts mock data: Adds it to internal data structures and prepares it for mocking. It potentially updates
1685
- * the overall mock data object later passed into jsonServer router as well as the rewrite object later
1686
- * passed into jsonServer.rewriter.
1687
- *
1688
- * @param key The key of the data
1689
- * @param data The data itself
1690
- * @param urlRedirects The redirect URLs to be rewritten to the key url
1691
- * @param crud Whether this is a crud redirect
1692
- * @returns The loaded mock data object
1693
- */
1694
- putMockData(key, data, urlRedirects, crud) {
1695
- this.addToMockData(key, data);
1696
- if (crud !== void 0) {
1697
- this.addToRedirects(key, urlRedirects, crud);
1698
- } else {
1699
- this.addToRedirects(key, urlRedirects, false);
1700
- }
1701
- }
1702
- addToRedirects(key, urlRedirects, crud) {
1703
- urlRedirects.forEach((urlRedirect) => this.redirectUrls[urlRedirect] = "/" + key);
1704
- if (crud) {
1705
- urlRedirects.forEach((urlRedirect) => this.redirectUrls[urlRedirect + "/:id"] = "/" + key + "/:id");
1706
- }
1707
- }
1708
- rewritePostToGet(url) {
1709
- this.useCors(url);
1710
- this.server.use(url, _MockServerBuilder.postRewriteToGet);
1711
- }
1712
- static set200WithData(res, data) {
1713
- res.status(200).jsonp({ content: data });
1714
- }
1715
- static respondWithError(res, componentId, messageId, httpStatus, op, message) {
1716
- res.status(httpStatus).jsonp({
1717
- messages: [
1718
- {
1719
- "code": {
1720
- "componentId": componentId,
1721
- "httpStatusCode": httpStatus,
1722
- "localCode": messageId,
1723
- "messageSeverity": "ERR",
1724
- "uniqueCode": componentId + messageId
1725
- },
1726
- "correlationId": "N/A",
1727
- "detailMessage": message,
1728
- "operation": op,
1729
- "timestamp": "2022-05-10T15:17:08Z"
1730
- }
1731
- ]
1732
- });
1733
- }
1734
- mockCall(url, callProcessor) {
1735
- this.useCors(url);
1736
- this.server.use(url, callProcessor);
1737
- }
1738
- mockCRUDMulti(urls, allElements, finder, operationDesc) {
1739
- urls.forEach((url) => this.mockCRUD(url, allElements, finder, operationDesc));
1740
- }
1741
- mockCRUD(url, allElements, finder, operationDesc) {
1742
- this.mockCall(`${url}${url.endsWith("/") ? "" : "/"}:id`, async (req, res, next) => {
1743
- const method = req.method;
1744
- const id = parseInt(req.params["id"]);
1745
- console.log(`Calling ${operationDesc} CRUD ${method} with id ${id}`);
1746
- if (method === "GET") {
1747
- let returnedEntity = finder(id);
1748
- _MockServerBuilder.set200WithData(res, returnedEntity);
1749
- } else {
1750
- _MockServerBuilder.set200WithData(res, {});
1751
- }
1752
- });
1753
- this.mockCall(`${url}`, async (req, res, next) => {
1754
- const method = req.method;
1755
- console.log(`Calling ${operationDesc} CRUD ${method}${method === "GET" ? " ALL" : ""}`);
1756
- if (method === "GET") {
1757
- _MockServerBuilder.set200WithData(res, allElements);
1758
- } else if (method === "PUT") {
1759
- _MockServerBuilder.set200WithData(res, req.body);
1760
- } else {
1761
- _MockServerBuilder.set200WithData(res, {});
1762
- }
1763
- });
1764
- }
1765
- start() {
1766
- console.log("Mock data keys: " + Object.keys(this.mockData));
1767
- console.log("Redirect URLs: ", this.redirectUrls);
1768
- const router = this.jsonServer.router(this.mockData);
1769
- const middlewares = this.jsonServer.defaults();
1770
- this.server.use(this.jsonServer.rewriter(this.redirectUrls));
1771
- Object.keys(this.redirectUrls).forEach((redirectUrl) => {
1772
- this.useCors(redirectUrl);
1773
- });
1774
- this.server.use(middlewares);
1775
- this.server.use(router);
1776
- router.render = function(req, res) {
1777
- res.jsonp({
1778
- content: res.locals.data
1779
- });
1780
- };
1781
- this.server.listen(this.port, () => {
1782
- console.log("JSON Server is running on port " + this.port);
1783
- });
1784
- }
1785
- useCors(url) {
1786
- console.log("Configuring CORS for: ", url);
1787
- this.server.use(url, _MockServerBuilder.allowCors);
1788
- }
1789
- static allowCors(req, res, next) {
1790
- res.header("Access-Control-Allow-Origin", "*");
1791
- res.header("Access-Control-Allow-Headers", "*");
1792
- res.header("Access-Control-Allow-Methods", "*");
1793
- next();
1794
- }
1795
- static postRewriteToGet(req, res, next) {
1796
- if (req.method === "POST") {
1797
- console.log(`Received POST request, rewriting to GET: ` + req.url);
1798
- req.method = "GET";
1799
- }
1800
- next();
1801
- }
1802
- };
1803
-
1804
- // src/utils/ViewTestWrapper.tsx
1805
- import { useState } from "react";
1806
- import { jsx } from "react/jsx-runtime";
1807
- function ViewTestWrapper(props) {
1808
- const [value, setValue] = useState(props.initialValue);
1809
- return /* @__PURE__ */ jsx("div", { children: props.view(value, (propertyName, changedValue) => setValue(changedValue)) });
1810
- }
1811
- export {
1812
- AbstractComponentTesting,
1813
- AbstractInputTesting,
1814
- AbstractSelectTesting,
1815
- AbstractViewTesting,
1816
- AlertTesting,
1817
- BoxTesting,
1818
- ButtonDropdownTesting,
1819
- ButtonTesting,
1820
- CSVNoItemsViewTesting,
1821
- CSVPriceInputViewTesting,
1822
- CSVSearchFilterViewTesting,
1823
- CSVTextPromptModalViewTesting,
1824
- CardsTesting,
1825
- CheckboxTesting,
1826
- CollectionPreferencesSetting,
1827
- CollectionPreferencesTesting,
1828
- DatePickerTesting,
1829
- FlashbarTesting,
1830
- FormTesting,
1831
- HeaderTesting,
1832
- IconTesting,
1833
- LinkTesting,
1834
- MockBrowserAPIs,
1835
- MockRestClient,
1836
- MockServerBuilder,
1837
- ModalTesting,
1838
- MultiselectTesting,
1839
- NumberInputTesting,
1840
- PaginationTesting,
1841
- ProgressBarTesting,
1842
- RatingTesting,
1843
- SegmentedControlTesting,
1844
- SelectTesting,
1845
- StatusIndicatorTesting,
1846
- StringInputTesting,
1847
- TableTesting,
1848
- TabsTesting,
1849
- TestLocalisation,
1850
- TestingFactory,
1851
- TextContentTesting,
1852
- TextFilterTesting,
1853
- TextareaTesting,
1854
- ToggleTesting,
1855
- ViewTestWrapper,
1856
- WizardTesting,
1857
- setupRestClientMock
1858
- };