forked from redhat-developer/rhdh-e2e-test-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui-helper.ts
More file actions
591 lines (518 loc) · 17.7 KB
/
Copy pathui-helper.ts
File metadata and controls
591 lines (518 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import type { Locator, Page } from "@playwright/test";
import { expect } from "@playwright/test";
import {
UI_HELPER_ELEMENTS,
WAIT_OBJECTS,
} from "../page-objects/global-obj.js";
import type { SidebarTabs } from "./navbar.js";
import { SEARCH_OBJECTS_COMPONENTS } from "../page-objects/page-obj.js";
export class UIhelper {
private page: Page;
constructor(page: Page) {
this.page = page;
}
async waitForLoad(timeout = 120000) {
for (const item of Object.values(WAIT_OBJECTS)) {
await this.page.waitForSelector(item, {
state: "hidden",
timeout: timeout,
});
}
}
/**
* Closes the quickstart drawer when the "Hide" button is visible (RHDH quickstart plugin),
* so it does not cover catalog or other UI under test.
*/
async dismissQuickstartIfVisible(options?: { waitHiddenMs?: number }) {
const waitHiddenMs = options?.waitHiddenMs ?? 5000;
const quickstartHide = this.page.getByRole("button", { name: "Hide" });
if (await quickstartHide.isVisible()) {
await quickstartHide.click();
await quickstartHide.waitFor({
state: "hidden",
timeout: waitHiddenMs,
});
}
}
async verifyComponentInCatalog(kind: string, expectedRows: string[]) {
await this.openSidebar("Catalog");
await this.selectMuiBox("Kind", kind);
await this.verifyRowsInTable(expectedRows);
}
getSideBarMenuItem(menuItem: string): Locator {
return this.page.getByTestId("login-button").getByText(menuItem);
}
async fillTextInputByLabel(label: string, text: string) {
await this.page.getByLabel(label).fill(text);
}
/**
* Fills the search input with the provided text.
*
* @param searchText - The text to be entered into the search input field.
*/
async searchInputPlaceholder(searchText: string) {
await this.page.fill(
SEARCH_OBJECTS_COMPONENTS.placeholderSearch,
searchText,
);
}
async searchInputAriaLabel(searchText: string) {
await this.page.fill(SEARCH_OBJECTS_COMPONENTS.ariaLabelSearch, searchText);
}
async pressTab() {
await this.page.keyboard.press("Tab");
}
async checkCheckbox(text: string) {
const locator = this.page.getByRole("checkbox", {
name: text,
});
await locator.check();
}
async uncheckCheckbox(text: string) {
const locator = this.page.getByRole("checkbox", {
name: text,
});
await locator.uncheck();
}
async clickButton(
label: string | RegExp,
options: { exact?: boolean; force?: boolean } = {
exact: true,
force: false,
},
) {
const button = this.page
.getByRole("button", { name: label, exact: options.exact })
.first();
await button.click({ force: options.force });
return button;
}
async clickBtnByTitleIfNotPressed(title: string) {
const button = this.page.locator(`button[title="${title}"]`);
const isPressed = await button.getAttribute("aria-pressed");
if (isPressed === "false") {
await button.click();
}
}
async clickByDataTestId(dataTestId: string) {
const element = this.page.getByTestId(dataTestId);
await element.waitFor({ state: "visible" });
await element.dispatchEvent("click");
}
/**
* Clicks on a button element by its text content, waiting for it to be visible first.
*
* @param buttonText - The text content of the button to click on.
* @param options - Optional configuration for exact match, timeout, and force click.
*/
async clickButtonByText(
buttonText: string | RegExp,
options: {
exact?: boolean;
timeout?: number;
force?: boolean;
} = {
exact: true,
timeout: 10000,
force: false,
},
) {
const buttonElement = this.page
.getByRole("button")
.getByText(buttonText, { exact: options.exact });
await buttonElement.waitFor({
state: "visible",
timeout: options.timeout,
});
if (options.force) {
await buttonElement.click({ force: true });
} else {
await buttonElement.click();
}
}
async clickButtonByLabel(label: string | RegExp) {
await this.page.getByRole("button", { name: label }).first().click();
}
async clickLink(options: string | { href: string } | { ariaLabel: string }) {
let linkLocator: Locator;
if (typeof options === "string") {
linkLocator = this.page.locator("a").filter({ hasText: options }).first();
} else if ("href" in options) {
linkLocator = this.page.locator(`a[href="${options.href}"]`).first();
} else {
linkLocator = this.page
.locator(`div[aria-label='${options.ariaLabel}'] a`)
.first();
}
await linkLocator.waitFor({ state: "visible" });
await linkLocator.click();
}
async openProfileDropdown() {
const header = this.page.locator("nav[id='global-header']");
await expect(header).toBeVisible();
await header
.locator("[data-testid='KeyboardArrowDownOutlinedIcon']")
.click();
}
async goToPageUrl(url: string, heading?: string) {
await this.page.goto(url);
await expect(this.page).toHaveURL(url);
await this.waitForLoad();
if (heading) {
await this.verifyHeading(heading);
}
}
async verifyLink(
arg: string | { label: string },
options: {
exact?: boolean;
notVisible?: boolean;
} = {
exact: true,
notVisible: false,
},
) {
let linkLocator: Locator;
let notVisibleCheck: boolean;
if (typeof arg != "object") {
linkLocator = this.page
.locator("a")
.getByText(arg, { exact: options.exact })
.first();
notVisibleCheck = options?.notVisible ?? false;
} else {
linkLocator = this.page.locator(`div[aria-label="${arg.label}"] a`);
notVisibleCheck = false;
}
if (notVisibleCheck) {
await expect(linkLocator).toBeHidden();
} else {
await expect(linkLocator).toBeVisible();
}
}
private async isElementVisible(
locator: string,
timeout = 10000,
force = false,
): Promise<boolean> {
try {
await this.page.waitForSelector(locator, {
state: "visible",
timeout: timeout,
});
const button = this.page.locator(locator).first();
return button.isVisible();
} catch (error) {
if (force) throw error;
return false;
}
}
async isBtnVisibleByTitle(text: string): Promise<boolean> {
const locator = `BUTTON[title="${text}"]`;
return await this.isElementVisible(locator);
}
async isBtnVisible(text: string): Promise<boolean> {
const locator = `button:has-text("${text}")`;
return await this.isElementVisible(locator);
}
async isTextVisible(text: string, timeout = 10000): Promise<boolean> {
const locator = `:has-text("${text}")`;
return await this.isElementVisible(locator, timeout);
}
async verifyTextVisible(
text: string,
exact = false,
timeout = 10000,
): Promise<void> {
const locator = this.page.getByText(text, { exact });
await expect(locator).toBeVisible({ timeout });
}
async verifyLinkVisible(text: string, timeout = 10000): Promise<void> {
const locator = this.page.locator(`a:has-text("${text}")`);
await expect(locator).toBeVisible({ timeout });
}
async openSidebar(navBarText: SidebarTabs) {
const navLink = this.page
.locator(`nav a:has-text("${navBarText}")`)
.first();
await navLink.waitFor({ state: "visible", timeout: 15_000 });
await navLink.dispatchEvent("click");
}
async openCatalogSidebar(kind: string) {
await this.openSidebar("Catalog");
await this.selectMuiBox("Kind", kind);
await expect(async () => {
await this.clickByDataTestId("user-picker-all");
await this.page.waitForTimeout(1_500);
await this.verifyHeading(new RegExp(`all ${kind}`, "i"));
}).toPass({
intervals: [3_000],
timeout: 20_000,
});
}
async openSidebarButton(navBarButtonLabel: string) {
const navLink = this.page.locator(
`nav button[aria-label="${navBarButtonLabel}"]`,
);
await navLink.waitFor({ state: "visible" });
await navLink.click();
}
async selectMuiBox(label: string, value: string) {
await this.page.click(`div[aria-label="${label}"]`);
const optionSelector = `li[role="option"]:has-text("${value}")`;
await this.page.waitForSelector(optionSelector);
await this.page.click(optionSelector);
}
async verifyRowsInTable(
rowTexts: (string | RegExp)[],
exact: boolean = true,
) {
for (const rowText of rowTexts) {
await this.verifyTextInLocator(`tr>td`, rowText, exact);
}
}
async waitForTextDisappear(text: string) {
await this.page.waitForSelector(`text=${text}`, { state: "detached" });
}
async verifyText(text: string | RegExp, exact: boolean = true) {
await this.verifyTextInLocator("", text, exact);
}
private async verifyTextInLocator(
locator: string,
text: string | RegExp,
exact: boolean,
) {
const elementLocator = locator
? this.page.locator(locator).getByText(text, { exact }).first()
: this.page.getByText(text, { exact }).first();
await elementLocator.waitFor({ state: "visible" });
await elementLocator.waitFor({ state: "attached" });
try {
await elementLocator.scrollIntoViewIfNeeded();
} catch (error) {
console.warn(
`Warning: Could not scroll element into view. Error: ${error instanceof Error ? error.message : String(error)}`,
);
}
await expect(elementLocator).toBeVisible();
}
async verifyTextInSelector(selector: string, expectedText: string) {
const elementLocator = this.page
.locator(selector)
.getByText(expectedText, { exact: true });
try {
await elementLocator.waitFor({ state: "visible" });
const actualText = (await elementLocator.textContent()) || "No content";
if (actualText.trim() !== expectedText.trim()) {
console.error(
`Verification failed for text: Expected "${expectedText}", but got "${actualText}"`,
);
throw new Error(
`Expected text "${expectedText}" not found. Actual content: "${actualText}".`,
);
}
console.log(
`Text "${expectedText}" verified successfully in selector: ${selector}`,
);
} catch (error) {
const allTextContent = await this.page
.locator(selector)
.allTextContents();
console.error(
`Verification failed for text: Expected "${expectedText}". Selector content: ${allTextContent.join(", ")}`,
);
throw error;
}
}
async verifyColumnHeading(
rowTexts: string[] | RegExp[],
exact: boolean = true,
) {
for (const rowText of rowTexts) {
const rowLocator = this.page
.locator(`tr>th`)
.getByText(rowText, { exact: exact })
.first();
await rowLocator.waitFor({ state: "visible" });
await rowLocator.scrollIntoViewIfNeeded();
await expect(rowLocator).toBeVisible();
}
}
async verifyHeading(heading: string | RegExp, timeout: number = 20000) {
const headingLocator = this.page
.locator("h1, h2, h3, h4, h5, h6")
.filter({ hasText: heading })
.first();
await headingLocator.waitFor({ state: "visible", timeout: timeout });
await expect(headingLocator).toBeVisible();
}
async verifyParagraph(paragraph: string) {
const headingLocator = this.page
.locator("p")
.filter({ hasText: paragraph })
.first();
await headingLocator.waitFor({ state: "visible", timeout: 20000 });
await expect(headingLocator).toBeVisible();
}
async waitForTitle(text: string, level: number = 1) {
await this.page.waitForSelector(`h${level}:has-text("${text}")`);
}
async clickTab(tabName: string) {
const tabLocator = this.page.getByRole("tab", { name: tabName });
await tabLocator.waitFor({ state: "visible" });
await tabLocator.click();
}
async verifyCellsInTable(texts: (string | RegExp)[]) {
for (const text of texts) {
const cellLocator = this.page
.locator(UI_HELPER_ELEMENTS.MuiTableCell)
.filter({ hasText: text });
const count = await cellLocator.count();
if (count === 0) {
throw new Error(
`Expected at least one cell with text matching ${text}, but none were found.`,
);
}
// Checks if all matching cells are visible.
for (let i = 0; i < count; i++) {
await expect(cellLocator.nth(i)).toBeVisible();
}
}
}
async verifyButtonURL(
label: string | RegExp,
url: string | RegExp,
options: { locator?: string; exact?: boolean } = {
locator: "",
exact: true,
},
) {
// To verify the button URL if it is in a specific locator
const baseLocator =
!options.locator || options.locator === ""
? this.page
: this.page.locator(options.locator);
const buttonUrl = await baseLocator
.getByRole("button", { name: label, exact: options.exact })
.first()
.getAttribute("href");
expect(buttonUrl).toContain(url);
}
/**
* Verifies that a table row, identified by unique text, contains specific cell texts.
* @param {string} uniqueRowText - The unique text present in one of the cells within the row. This is used to identify the specific row.
* @param {Array<string | RegExp>} cellTexts - An array of cell texts or regular expressions to match against the cells within the identified row.
* @example
* // Example usage to verify that a row containing "Developer-hub" has cells with the texts "service" and "active":
* await verifyRowInTableByUniqueText('Developer-hub', ['service', 'active']);
*/
async verifyRowInTableByUniqueText(
uniqueRowText: string,
cellTexts: string[] | RegExp[],
) {
const row = this.page.locator(UI_HELPER_ELEMENTS.rowByText(uniqueRowText));
await row.waitFor();
for (const cellText of cellTexts) {
await expect(
row.locator("td").filter({ hasText: cellText }).first(),
).toBeVisible();
}
}
/**
* Clicks on a link within a table row that contains a unique text and matches a link's text.
* @param {string} uniqueRowText - The unique text present in one of the cells within the row. This is used to identify the specific row.
* @param {string | RegExp} linkText - The text of the link, can be a string or a regular expression.
* @param {boolean} [exact=true] - Whether to match the link text exactly. By default, this is set to true.
*/
async clickOnLinkInTableByUniqueText(
uniqueRowText: string,
linkText: string | RegExp,
exact: boolean = true,
) {
const row = this.page.locator(UI_HELPER_ELEMENTS.rowByText(uniqueRowText));
await row.waitFor();
await row
.locator("a")
.getByText(linkText, { exact: exact })
.first()
.click();
}
/**
* Clicks on a button within a table row that contains a unique text and matches a button's label or aria-label.
* @param {string} uniqueRowText - The unique text present in one of the cells within the row. This is used to identify the specific row.
* @param {string | RegExp} textOrLabel - The text of the button or the `aria-label` attribute, can be a string or a regular expression.
*/
async clickOnButtonInTableByUniqueText(
uniqueRowText: string,
textOrLabel: string | RegExp,
) {
const row = this.page.locator(UI_HELPER_ELEMENTS.rowByText(uniqueRowText));
await row.waitFor();
await row
.locator(
`button:has-text("${textOrLabel}"), button[aria-label="${textOrLabel}"]`,
)
.first()
.click();
}
async verifyLinkinCard(cardHeading: string, linkText: string, exact = true) {
const link = this.page
.locator(UI_HELPER_ELEMENTS.MuiCard(cardHeading))
.locator("a")
.getByText(linkText, { exact: exact })
.first();
await link.scrollIntoViewIfNeeded();
await expect(link).toBeVisible();
}
async clickBtnInCard(cardText: string, btnText: string, exact = true) {
const cardLocator = this.page
.locator(UI_HELPER_ELEMENTS.MuiCardRoot(cardText))
.first();
await cardLocator.scrollIntoViewIfNeeded();
await cardLocator
.getByRole("button", { name: btnText, exact: exact })
.first()
.click();
}
async verifyTextinCard(
cardHeading: string,
text: string | RegExp,
exact = true,
) {
const locator = this.page
.locator(UI_HELPER_ELEMENTS.MuiCard(cardHeading))
.getByText(text, { exact: exact })
.first();
await locator.scrollIntoViewIfNeeded();
await expect(locator).toBeVisible();
}
async verifyTableHeadingAndRows(texts: string[]) {
// Wait for the table to load by checking for the presence of table rows
await this.page.waitForSelector("table tbody tr", { state: "visible" });
for (const column of texts) {
const columnSelector = `table th:has-text("${column}")`;
//check if columnSelector has at least one element or more
const columnCount = await this.page.locator(columnSelector).count();
expect(columnCount).toBeGreaterThan(0);
}
// Checks if the table has at least one row with data
// Excludes rows that have cells spanning multiple columns, such as "No data available" messages
const rowSelector = `table tbody tr:not(:has(td[colspan]))`;
const rowCount = await this.page.locator(rowSelector).count();
expect(rowCount).toBeGreaterThan(0);
}
async verifyTableIsEmpty() {
const rowSelector = `table tbody tr:not(:has(td[colspan]))`;
const rowCount = await this.page.locator(rowSelector).count();
expect(rowCount).toEqual(0);
}
async verifyAlertErrorMessage(message: string | RegExp) {
const alert = this.page.getByRole("alert");
await alert.waitFor();
await expect(alert).toHaveText(message);
}
async verifyTextInTooltip(text: string | RegExp) {
const tooltip = this.page.getByRole("tooltip").getByText(text);
await expect(tooltip).toBeVisible();
}
}