From d569d971f4665e9ca5f0731b27f4be24ad9b6d44 Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Wed, 2 Sep 2026 15:18:05 +0200 Subject: [PATCH 01/21] Improve Admin UI stability for Playwright E2E tests Add LoadingOverlay with PatternFly Skeleton and testable loading signals. Keep KeycloakDataTable DOM mounted during reload, normalize switch handling, and add readiness markers for tabs, users list, and auth flow reordering. Simplify Playwright helpers to use waitForLoadingComplete instead of multi-attempt retry loops. Closes #52322 Signed-off-by: Erik Jan de Wit --- js/apps/admin-ui/README.md | 19 +++ .../src/authentication/FlowDetails.tsx | 140 +++++++++-------- .../src/authentication/components/FlowRow.tsx | 6 +- .../admin-ui/src/clients/ClientDetails.tsx | 6 +- .../admin-ui/src/clients/keys/SamlKeys.tsx | 5 + .../src/components/users/UserDataTable.tsx | 132 ++++++++-------- .../identity-providers/add/DetailSettings.tsx | 16 +- .../component/SwitchField.tsx | 8 +- .../admin-ui/src/realm-settings/LoginTab.tsx | 145 ++++++++++++----- .../src/realm-settings/PoliciesTab.tsx | 2 +- js/apps/admin-ui/src/user/EditUser.tsx | 6 +- .../src/workflows/WorkflowsSection.tsx | 23 ++- js/apps/admin-ui/test/autentication/flow.ts | 148 +++++------------- .../admin-ui/test/identity-providers/main.ts | 4 +- .../test/identity-providers/saml.spec.ts | 10 +- .../test/realm-settings/userprofile.ts | 9 +- js/apps/admin-ui/test/utils/loading.ts | 9 ++ js/apps/admin-ui/test/utils/modal.ts | 8 +- js/apps/admin-ui/test/utils/table.ts | 46 ++---- js/apps/admin-ui/test/workflows/main.spec.ts | 4 +- .../src/buttons/FormSubmitButton.tsx | 1 + .../continue-cancel/ContinueCancelModal.tsx | 2 + .../src/controls/KeycloakSpinner.tsx | 2 +- .../ui-shared/src/controls/LoadingOverlay.tsx | 54 +++++++ .../ui-shared/src/controls/SwitchControl.tsx | 3 + .../src/controls/loading-overlay.module.css | 34 ++++ .../src/controls/table/KeycloakDataTable.tsx | 96 +++++++----- js/libs/ui-shared/src/main.ts | 4 + 28 files changed, 554 insertions(+), 388 deletions(-) create mode 100644 js/apps/admin-ui/test/utils/loading.ts create mode 100644 js/libs/ui-shared/src/controls/LoadingOverlay.tsx create mode 100644 js/libs/ui-shared/src/controls/loading-overlay.module.css diff --git a/js/apps/admin-ui/README.md b/js/apps/admin-ui/README.md index 44cc7c762dd..aba7c0b3310 100644 --- a/js/apps/admin-ui/README.md +++ b/js/apps/admin-ui/README.md @@ -61,6 +61,25 @@ The Playwright tests under `js/apps/admin-ui/test` accept these environment vari These test-only variables are different from server bootstrap variables such as `KC_BOOTSTRAP_ADMIN_USERNAME` and `KC_BOOTSTRAP_ADMIN_PASSWORD`. +## Playwright loading conventions + +Async UI in the admin console exposes stable loading signals for E2E tests: + +- `data-testid="loading-spinner"` — present on the loading overlay while a section or table is fetching (`LoadingOverlay` skeleton). +- `aria-busy="true"` — set on `LoadingOverlay` containers during fetch. +- `data-testid="table-ready"` — set on `KeycloakDataTable` when the current fetch has completed. + +Use `waitForLoadingComplete` from `test/utils/loading.ts` before interacting with tables or forms inside a loading scope: + +```ts +import { waitForLoadingComplete } from "./utils/loading.ts"; + +await waitForLoadingComplete(page); +await page.locator("table tbody").getByRole("link", { name: itemName }).click(); +``` + +Wait for spinner absence rather than polling `table tbody` visibility, because tables stay mounted during reload. + ## Building To build a library instead of an app you need to add the `LIB=true` environment variable. diff --git a/js/apps/admin-ui/src/authentication/FlowDetails.tsx b/js/apps/admin-ui/src/authentication/FlowDetails.tsx index cfbc7cab05c..30af9001164 100644 --- a/js/apps/admin-ui/src/authentication/FlowDetails.tsx +++ b/js/apps/admin-ui/src/authentication/FlowDetails.tsx @@ -66,6 +66,7 @@ export default function FlowDetails() { const [flow, setFlow] = useState(); const [executionList, setExecutionList] = useState(); const [liveText, setLiveText] = useState(""); + const [isReordering, setIsReordering] = useState(false); const [showAddExecutionDialog, setShowAddExecutionDialog] = useState(); @@ -409,74 +410,85 @@ export default function FlowDetails() { {tableView && ( - { - const item = executionList.findExecution(index)!; - setLiveText(t("onDragStart", { item: item.displayName })); - if (!item.isCollapsed) { - item.isCollapsed = true; - setExecutionList(executionList.clone()); - } - return true; - }} - onDragMove={({ index }) => { - const dragged = executionList.findExecution(index); - setLiveText(t("onDragMove", { item: dragged?.displayName })); - }} - onDrop={(source, dest) => { - if (dest) { - if (source.index === dest.index) { - return false; +
+ { + const item = executionList.findExecution(index)!; + setLiveText(t("onDragStart", { item: item.displayName })); + if (!item.isCollapsed) { + item.isCollapsed = true; + setExecutionList(executionList.clone()); } - - const dragged = executionList.findExecution(source.index)!; - const order = executionList.order().map((ex) => ex.id!); + return true; + }} + onDragMove={({ index }) => { + const dragged = executionList.findExecution(index); setLiveText( - t("onDragFinish", { list: dragged.displayName }), + t("onDragMove", { item: dragged?.displayName }), ); + }} + onDrop={(source, dest) => { + if (dest) { + if (source.index === dest.index) { + return false; + } - const [removed] = order.splice(source.index, 1); - order.splice(dest.index, 0, removed); - const change = executionList.getChange(dragged, order); - void executeChange(dragged, change); - return true; - } else { - setLiveText(t("onDragCancel")); - return false; - } - }} - > - - - - <> - {executionList.expandableList.map((execution) => ( - - { - execution.isCollapsed = !execution.isCollapsed; - setExecutionList(executionList.clone()); - }} - onRowChange={update} - onAddExecution={(execution, type) => - addExecution(execution.displayName!, type) - } - onAddFlow={(execution, flow) => - addFlow(execution.displayName!, flow) - } - onDelete={(execution) => { - setSelectedExecution(execution); - toggleDeleteDialog(); - }} - /> - - ))} - -
-
-
+ const dragged = executionList.findExecution( + source.index, + )!; + const order = executionList.order().map((ex) => ex.id!); + setLiveText( + t("onDragFinish", { list: dragged.displayName }), + ); + + const [removed] = order.splice(source.index, 1); + order.splice(dest.index, 0, removed); + const change = executionList.getChange(dragged, order); + setIsReordering(true); + void executeChange(dragged, change).finally(() => + setIsReordering(false), + ); + return true; + } else { + setLiveText(t("onDragCancel")); + return false; + } + }} + > + + + + <> + {executionList.expandableList.map((execution) => ( + + { + execution.isCollapsed = !execution.isCollapsed; + setExecutionList(executionList.clone()); + }} + onRowChange={update} + onAddExecution={(execution, type) => + addExecution(execution.displayName!, type) + } + onAddFlow={(execution, flow) => + addFlow(execution.displayName!, flow) + } + onDelete={(execution) => { + setSelectedExecution(execution); + toggleDeleteDialog(); + }} + /> + + ))} + +
+
+ +
)} {flow && ( <> diff --git a/js/apps/admin-ui/src/authentication/components/FlowRow.tsx b/js/apps/admin-ui/src/authentication/components/FlowRow.tsx index 9e4bdae6d0d..7ec1829e2f3 100644 --- a/js/apps/admin-ui/src/authentication/components/FlowRow.tsx +++ b/js/apps/admin-ui/src/authentication/components/FlowRow.tsx @@ -66,7 +66,11 @@ export const FlowRow = ({ return ( <> - + )} /> - + { } save(); }, + onCancel: () => { + if (selectedType) { + setValue(KEYS_MAPPING[selectedType].name, "true"); + } + }, }); const regenerateKey = selectedType diff --git a/js/apps/admin-ui/src/components/users/UserDataTable.tsx b/js/apps/admin-ui/src/components/users/UserDataTable.tsx index 383fff5e16a..4fbe7ef24ff 100644 --- a/js/apps/admin-ui/src/components/users/UserDataTable.tsx +++ b/js/apps/admin-ui/src/components/users/UserDataTable.tsx @@ -351,72 +351,74 @@ export function UserDataTable() { <> - setSelectedRows([...rows])} - emptyState={ - !listUsers ? ( - <> - - {toolbar()} - - - - {t("searchForUserDescription")} - - - - ) : ( - - ) - } - toolbarItem={toolbar()} - subToolbar={subtoolbar()} - actionResolver={(rowData: IRowData) => [ - { - title: t("delete"), - onClick: () => { - setSelectedRows([rowData.data]); - toggleDeleteDialog(); +
+ setSelectedRows([...rows])} + emptyState={ + !listUsers ? ( + <> + + {toolbar()} + + + + {t("searchForUserDescription")} + + + + ) : ( + + ) + } + toolbarItem={toolbar()} + subToolbar={subtoolbar()} + actionResolver={(rowData: IRowData) => [ + { + title: t("delete"), + onClick: () => { + setSelectedRows([rowData.data]); + toggleDeleteDialog(); + }, }, - }, - ]} - isRowDisabled={(user: UserRepresentation) => !user.access?.manage} - columns={[ - { - name: "username", - displayKey: "username", - cellRenderer: UserDetailLink, - }, - { - name: "email", - displayKey: "email", - cellRenderer: ValidatedEmail, - }, - { - name: "lastName", - displayKey: "lastName", - cellFormatters: [emptyFormatter()], - }, - { - name: "firstName", - displayKey: "firstName", - cellFormatters: [emptyFormatter()], - }, - ]} - /> + ]} + isRowDisabled={(user: UserRepresentation) => !user.access?.manage} + columns={[ + { + name: "username", + displayKey: "username", + cellRenderer: UserDetailLink, + }, + { + name: "email", + displayKey: "email", + cellRenderer: ValidatedEmail, + }, + { + name: "lastName", + displayKey: "lastName", + cellFormatters: [emptyFormatter()], + }, + { + name: "firstName", + displayKey: "firstName", + cellFormatters: [emptyFormatter()], + }, + ]} + /> +
); } diff --git a/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx b/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx index 25e3397bc92..ddabfd5dbed 100644 --- a/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx +++ b/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx @@ -25,7 +25,7 @@ import { Text, ToolbarItem, } from "@patternfly/react-core"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { Controller, FormProvider, @@ -34,7 +34,7 @@ import { useWatch, } from "react-hook-form"; import { useTranslation } from "react-i18next"; -import { Link, useNavigate } from "react-router-dom"; +import { Link, useLocation, useNavigate } from "react-router-dom"; import { useAdminClient } from "../../admin-client"; import { useConfirmDialog } from "../../components/confirm-dialog/ConfirmDialog"; import { DynamicComponents } from "../../components/dynamic/DynamicComponents"; @@ -347,9 +347,10 @@ export default function DetailSettings() { const { addAlert, addError } = useAlerts(); const navigate = useNavigate(); + const location = useLocation(); const { realm, realmRepresentation } = useRealm(); const [key, setKey] = useState(0); - const refresh = () => setKey(key + 1); + const refresh = () => setKey((current) => current + 1); const [orgSubTab, setOrgSubTab] = useState("org-list"); const { hasAccess } = useAccess(); @@ -396,6 +397,12 @@ export default function DetailSettings() { const permissionsTab = useTab("permissions"); const eventsTab = useTab("events"); + useEffect(() => { + if (location.pathname.endsWith("/mappers")) { + refresh(); + } + }, [location.pathname]); + const save = async (savedProvider?: IdentityProviderRepresentation) => { const p = convertFormValuesToObject( savedProvider || getValues(), @@ -860,8 +867,7 @@ export default function DetailSettings() { } /> } - loader={loader} - key={key} + loader={{ signal: key, loader }} ariaLabelKey="mappersList" searchPlaceholderKey="searchForMapper" toolbarItem={ diff --git a/js/apps/admin-ui/src/identity-providers/component/SwitchField.tsx b/js/apps/admin-ui/src/identity-providers/component/SwitchField.tsx index aa6c1f38fe0..7ae3674b771 100644 --- a/js/apps/admin-ui/src/identity-providers/component/SwitchField.tsx +++ b/js/apps/admin-ui/src/identity-providers/component/SwitchField.tsx @@ -1,6 +1,7 @@ import { Switch } from "@patternfly/react-core"; import { Controller, useFormContext } from "react-hook-form"; import { useTranslation } from "react-i18next"; +import { debeerify } from "@keycloak/keycloak-ui-shared"; import { FieldProps, FormGroupField } from "./FormGroupField"; @@ -13,7 +14,7 @@ type SwitchFieldProps = FieldProps & { export const SwitchField = ({ label, - field, + field: fieldName, fieldType = "string", isReadOnly = false, defaultValue, @@ -23,14 +24,15 @@ export const SwitchField = ({ return ( ( { - const name = Array.isArray(switches) - ? Object.keys(switches[0])[0] - : Object.keys(switches)[0]; + const [savingFields, setSavingFields] = useState>(new Set()); + const setSaving = (field: string, saving: boolean) => { + setSavingFields((prev) => { + const next = new Set(prev); + if (saving) { + next.add(field); + } else { + next.delete(field); + } + return next; + }); + }; + + const updateSwitchValue = async ( + switches: SwitchType | SwitchType[], + fieldKey?: string, + ) => { + const name = + fieldKey ?? + (Array.isArray(switches) + ? Object.keys(switches[0])[0] + : Object.keys(switches)[0]); + + setSaving(name, true); try { await adminClient.realms.update( { @@ -47,6 +68,8 @@ export const RealmSettingsLoginTab = ({ refresh(); } catch (error) { addError("enableSwitchError", error); + } finally { + setSaving(name, false); } }; @@ -59,7 +82,7 @@ export const RealmSettingsLoginTab = ({ { - await updateSwitchValue({ registrationAllowed: value }); + await updateSwitchValue( + { registrationAllowed: value }, + "registrationAllowed", + ); }} aria-label={t("registrationAllowed")} /> { - await updateSwitchValue({ resetPasswordAllowed: value }); + await updateSwitchValue( + { resetPasswordAllowed: value }, + "resetPasswordAllowed", + ); }} aria-label={t("resetPasswordAllowed")} /> { - await updateSwitchValue({ rememberMe: value }); + await updateSwitchValue({ rememberMe: value }, "rememberMe"); }} aria-label={t("rememberMe")} /> @@ -133,7 +168,7 @@ export const RealmSettingsLoginTab = ({ {passkeysVisible && ( { - await updateSwitchValue({ - webAuthnPolicyPasswordlessPasskeysEnabled: value, - }); + await updateSwitchValue( + { + webAuthnPolicyPasswordlessPasskeysEnabled: value, + }, + "webAuthnPolicyPasswordlessPasskeysEnabled", + ); }} aria-label={t("webAuthnPolicyPasskeysEnabled")} />{" "} @@ -178,7 +222,7 @@ export const RealmSettingsLoginTab = ({ { - await updateSwitchValue([ - { - registrationEmailAsUsername: value, - }, - { - duplicateEmailsAllowed: false, - }, - ]); + await updateSwitchValue( + [ + { + registrationEmailAsUsername: value, + }, + { + duplicateEmailsAllowed: false, + }, + ], + "registrationEmailAsUsername", + ); }} aria-label={t("registrationEmailAsUsername")} /> { - await updateSwitchValue([ - { - loginWithEmailAllowed: value, - }, - { duplicateEmailsAllowed: false }, - ]); + await updateSwitchValue( + [ + { + loginWithEmailAllowed: value, + }, + { duplicateEmailsAllowed: false }, + ], + "loginWithEmailAllowed", + ); }} aria-label={t("loginWithEmailAllowed")} /> { - await updateSwitchValue({ - duplicateEmailsAllowed: value, - }); + await updateSwitchValue( + { + duplicateEmailsAllowed: value, + }, + "duplicateEmailsAllowed", + ); }} isDisabled={ - realm.loginWithEmailAllowed || realm.registrationEmailAsUsername + realm.loginWithEmailAllowed || + realm.registrationEmailAsUsername || + savingFields.has("duplicateEmailsAllowed") } + aria-busy={savingFields.has("duplicateEmailsAllowed")} aria-label={t("duplicateEmailsAllowed")} /> { - await updateSwitchValue({ verifyEmail: value }); + await updateSwitchValue({ verifyEmail: value }, "verifyEmail"); }} aria-label={t("verifyEmail")} /> @@ -298,7 +360,7 @@ export const RealmSettingsLoginTab = ({ { - await updateSwitchValue({ editUsernameAllowed: value }); + await updateSwitchValue( + { editUsernameAllowed: value }, + "editUsernameAllowed", + ); }} aria-label={t("editUsernameAllowed")} /> diff --git a/js/apps/admin-ui/src/realm-settings/PoliciesTab.tsx b/js/apps/admin-ui/src/realm-settings/PoliciesTab.tsx index 4b2fa1aee2e..30b52b7c825 100644 --- a/js/apps/admin-ui/src/realm-settings/PoliciesTab.tsx +++ b/js/apps/admin-ui/src/realm-settings/PoliciesTab.tsx @@ -348,11 +348,11 @@ const SwitchRenderer = ({ ( - + setKey(key + 1); - - const [selectedWorkflow, setSelectedWorkflow] = - useState(); + const [refreshSignal, setRefreshSignal] = useState(0); + const [togglingWorkflowId, setTogglingWorkflowId] = useState(); const loader = async () => { const workflows = await adminClient.workflows.find(); @@ -50,6 +47,7 @@ export default function WorkflowsSection() { const toggleEnabled = async (workflow: WorkflowRepresentation) => { const enabled = !(workflow.enabled ?? true); const workflowToUpdate = { ...workflow, enabled }; + setTogglingWorkflowId(workflow.id); try { await adminClient.workflows.update( { id: workflow.id! }, @@ -60,12 +58,19 @@ export default function WorkflowsSection() { workflowToUpdate.enabled ? t("workflowEnabled") : t("workflowDisabled"), AlertVariant.success, ); - refresh(); + setRefreshSignal((signal) => signal + 1); } catch (error) { addError("workflowUpdateError", error); + } finally { + setTogglingWorkflowId(undefined); } }; + const [selectedWorkflow, setSelectedWorkflow] = + useState(); + + const refresh = () => setRefreshSignal((signal) => signal + 1); + const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({ titleKey: "workflowDeleteConfirm", messageKey: t("workflowDeleteConfirmDialog", { @@ -95,7 +100,7 @@ export default function WorkflowsSection() { ( toggleEnabled(workflow)} /> ), @@ -157,7 +165,6 @@ export default function WorkflowsSection() { }, } as Action, ]} - loader={loader} ariaLabelKey="workflows" emptyState={ { }; export async function clickSwitchPolicy(page: Page, policyName: string) { - await getEnabledSwitch(page, policyName).click({ force: true }); + await getEnabledSwitch(page, policyName).click(); } export async function clickDefaultSwitchPolicy(page: Page, policyName: string) { - await getDefaultSwitch(page, policyName).click({ force: true }); + await getDefaultSwitch(page, policyName).click(); } export async function assertSwitchPolicyChecked( page: Page, policyName: string, + checked = true, ) { - await expect(getEnabledSwitch(page, policyName)).toBeChecked(); + if (checked) { + await expect(getEnabledSwitch(page, policyName)).toBeChecked(); + } else { + await expect(getEnabledSwitch(page, policyName)).not.toBeChecked(); + } +} + +export async function assertDefaultSwitchPolicyChecked( + page: Page, + policyName: string, + checked = true, +) { + if (checked) { + await expect(getDefaultSwitch(page, policyName)).toBeChecked(); + } else { + await expect(getDefaultSwitch(page, policyName)).not.toBeChecked(); + } +} + +export async function assertSwitchPolicyEnabled( + page: Page, + policyName: string, +) { + await expect(getEnabledSwitch(page, policyName)).toBeEnabled(); } export async function assertDefaultSwitchPolicyEnabled( @@ -170,15 +194,13 @@ export async function dragExecutionAboveExecution( .first(); const getDragHandle = (row: Locator) => row.getByRole("button", { name: /draggable row/i }).first(); - const sourceHandle = getDragHandle(sourceRow); - const targetHandle = getDragHandle(targetRow); await expect(sourceRow).toBeVisible({ timeout: 5_000 }); await expect(targetRow).toBeVisible({ timeout: 5_000 }); + + const sourceHandle = getDragHandle(sourceRow); await expect(sourceHandle).toBeVisible({ timeout: 5_000 }); - await expect(targetHandle).toBeVisible({ timeout: 5_000 }); await sourceHandle.scrollIntoViewIfNeeded(); - await targetHandle.scrollIntoViewIfNeeded(); const getRowOrder = async () => { const rows = await treeGrid.getByRole("row").allInnerTexts(); @@ -189,7 +211,6 @@ export async function dragExecutionAboveExecution( }; const initialOrder = await getRowOrder(); - // Guard against upstream flow-order changes that could turn this test into a no-op. expect( initialOrder.sourceIndex, `Expected "${sourceExecution}" to start below "${targetExecution}" so drag can be verified`, @@ -205,105 +226,22 @@ export async function dragExecutionAboveExecution( ); }; - const waitForMove = async () => { - try { - await expect.poll(hasMoved, { timeout: 4_000 }).toBe(true); - return true; - } catch { - return false; - } - }; - - let moved = false; - - // Legacy pointer drag path works more reliably with some CI/browser combos. - const sourceText = sourceRow.getByText(sourceExecution).first(); - const targetText = targetRow.getByText(targetExecution).first(); - const sourceTextBox = await sourceText.boundingBox(); - const targetTextBox = await targetText.boundingBox(); - if (sourceTextBox && targetTextBox) { - await page.mouse.move( - sourceTextBox.x + sourceTextBox.width / 2, - sourceTextBox.y + sourceTextBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - targetTextBox.x + targetTextBox.width / 2, - targetTextBox.y + targetTextBox.height / 2, - { steps: 20 }, - ); - await page.mouse.up(); - moved = await waitForMove(); - } - - try { - if (!moved) { - await sourceHandle.dragTo(targetHandle, { timeout: 3_000 }); - moved = await waitForMove(); - } - } catch { - // Fall back to pointer/keyboard paths when dnd-kit does not trigger drag events in CI. - } - - if (!moved) { - const sourceBox = - (await sourceHandle.boundingBox()) ?? (await sourceRow.boundingBox()); - const targetBox = - (await targetHandle.boundingBox()) ?? (await targetRow.boundingBox()); - - if (sourceBox && targetBox) { - await page.mouse.move( - sourceBox.x + sourceBox.width / 2, - sourceBox.y + sourceBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - targetBox.x + targetBox.width / 2, - targetBox.y + Math.min(8, Math.max(2, targetBox.height / 4)), - { steps: 20 }, - ); - await page.mouse.up(); - moved = await waitForMove(); - } - } + await sourceHandle.focus(); + await page.keyboard.press("Space"); - if (!moved) { - try { - await sourceRow.dragTo(targetRow, { timeout: 3_000 }); - moved = await waitForMove(); - } catch { - // Keep trying keyboard fallback below. - } - } - - if (!moved) { - try { - await sourceHandle.focus({ timeout: 2_000 }); - await page.keyboard.press("Space"); - const rows = await treeGrid.getByRole("row").allInnerTexts(); - const sourceIndex = rows.findIndex((row) => - row.includes(sourceExecution), - ); - const targetIndex = rows.findIndex((row) => - row.includes(targetExecution), - ); - const steps = - sourceIndex !== -1 && targetIndex !== -1 && sourceIndex > targetIndex - ? sourceIndex - targetIndex - : 1; - for (let step = 0; step < steps; step++) { - await page.keyboard.press("ArrowUp"); - } - await page.keyboard.press("Space"); - moved = await waitForMove(); - } catch { - // Keep "moved" false and let the caller assert/fail with context. - } - } + const rows = await treeGrid.getByRole("row").allInnerTexts(); + const sourceIndex = rows.findIndex((row) => row.includes(sourceExecution)); + const targetIndex = rows.findIndex((row) => row.includes(targetExecution)); + const steps = + sourceIndex !== -1 && targetIndex !== -1 && sourceIndex > targetIndex + ? sourceIndex - targetIndex + : 1; - if (!moved) { - moved = await waitForMove(); + for (let step = 0; step < steps; step++) { + await page.keyboard.press("ArrowUp"); } + await page.keyboard.press("Space"); - return moved; + await expect.poll(hasMoved, { timeout: 8_000 }).toBe(true); + await expect(page.getByTestId("flow-order-stable")).toBeVisible(); } diff --git a/js/apps/admin-ui/test/identity-providers/main.ts b/js/apps/admin-ui/test/identity-providers/main.ts index 25b393ef7ba..738336881e3 100644 --- a/js/apps/admin-ui/test/identity-providers/main.ts +++ b/js/apps/admin-ui/test/identity-providers/main.ts @@ -1,6 +1,7 @@ import { type Page, expect } from "@playwright/test"; import { selectItem } from "../utils/form.ts"; import { assertNotificationMessage } from "../utils/masthead.ts"; +import { waitForLoadingComplete } from "../utils/loading.ts"; import { SERVER_URL } from "../utils/constants.ts"; const discoveryUrl = `${SERVER_URL}/realms/master/.well-known/openid-configuration`; @@ -80,7 +81,7 @@ export async function createJwtAuthorizationGrantProviderKey( await clickProviderCard(page, providerName); await page.getByTestId("config.issuer").fill(issuer); await expect(page.getByTestId("config.useJwksUrl")).toBeChecked(); - await page.getByTestId("config.useJwksUrl").click({ force: true }); + await page.getByTestId("config.useJwksUrl").click(); await expect( page.getByTestId("config.publicKeySignatureVerifierKeyId"), ).toBeVisible(); @@ -229,6 +230,7 @@ export async function clickSaveMapper(page: Page) { await expect(page).toHaveURL(/.*mappers$/); } } + await waitForLoadingComplete(page); } export async function clickCancelMapper(page: Page) { diff --git a/js/apps/admin-ui/test/identity-providers/saml.spec.ts b/js/apps/admin-ui/test/identity-providers/saml.spec.ts index 6e5aaedab24..40a27387693 100644 --- a/js/apps/admin-ui/test/identity-providers/saml.spec.ts +++ b/js/apps/admin-ui/test/identity-providers/saml.spec.ts @@ -1,9 +1,9 @@ -import { expect, test } from "@playwright/test"; +import { test } from "@playwright/test"; import { v4 as uuid } from "uuid"; import adminClient from "../utils/AdminClient.ts"; import { login } from "../utils/login.ts"; import { assertNotificationMessage } from "../utils/masthead.ts"; -import { clickTableRowItem } from "../utils/table.ts"; +import { assertRowExists, clickTableRowItem } from "../utils/table.ts"; import { addAuthConstraints, addMapper, @@ -83,11 +83,7 @@ test.describe.serial("SAML identity provider test", () => { await goToMappersTab(page); await addMapper(page, type, name); await clickSaveMapper(page); - await expect( - page.getByRole("row", { - name: new RegExp(name, "i"), - }), - ).toBeVisible(); + await assertRowExists(page, name); }); } diff --git a/js/apps/admin-ui/test/realm-settings/userprofile.ts b/js/apps/admin-ui/test/realm-settings/userprofile.ts index 16a8491c9db..0216b9d1cba 100644 --- a/js/apps/admin-ui/test/realm-settings/userprofile.ts +++ b/js/apps/admin-ui/test/realm-settings/userprofile.ts @@ -1,4 +1,5 @@ import { expect, type Page } from "@playwright/test"; +import { switchOff } from "../utils/form.ts"; export async function goToUserProfileTab(page: Page) { await page.getByTestId("rs-user-profile-tab").click(); @@ -47,12 +48,16 @@ export async function goToAttributeGroupsTab(page: Page) { } export async function switchOffIfOn(page: Page, selector: string) { - if (await page.isChecked(selector)) { - await page.locator(selector).click({ force: true }); + const switchElement = page.locator(selector); + if (await switchElement.isChecked()) { + await switchOff(page, switchElement); } } export async function clickCreateUser(page: Page) { + await expect(page.getByTestId("users-table-ready")).toBeVisible({ + timeout: 15_000, + }); const emptyAction = page.getByTestId("no-users-found-empty-action"); const addUser = page.getByTestId("add-user"); // The table briefly shows its empty state before the spinner appears, so don't decide on a single look. diff --git a/js/apps/admin-ui/test/utils/loading.ts b/js/apps/admin-ui/test/utils/loading.ts new file mode 100644 index 00000000000..437550d089a --- /dev/null +++ b/js/apps/admin-ui/test/utils/loading.ts @@ -0,0 +1,9 @@ +import { expect, type Locator, type Page } from "@playwright/test"; + +export async function waitForLoadingComplete( + page: Page, + scope?: Locator, +): Promise { + const root = scope ?? page; + await expect(root.getByTestId("loading-spinner")).toHaveCount(0); +} diff --git a/js/apps/admin-ui/test/utils/modal.ts b/js/apps/admin-ui/test/utils/modal.ts index f2f33118040..255713dbe13 100644 --- a/js/apps/admin-ui/test/utils/modal.ts +++ b/js/apps/admin-ui/test/utils/modal.ts @@ -9,11 +9,15 @@ export async function assertModalMessage(page: Page, message: string) { } export async function confirmModal(page: Page) { - await page.getByTestId("confirm").click(); + const confirm = page.getByTestId("confirm"); + await expect(confirm).toBeVisible(); + await confirm.click(); } export async function cancelModal(page: Page) { - await page.getByTestId("cancel").click(); + const cancel = page.getByTestId("cancel"); + await expect(cancel).toBeVisible(); + await cancel.click(); } export async function clickAdd(page: Page) { diff --git a/js/apps/admin-ui/test/utils/table.ts b/js/apps/admin-ui/test/utils/table.ts index c611ade8016..aec3d14506f 100644 --- a/js/apps/admin-ui/test/utils/table.ts +++ b/js/apps/admin-ui/test/utils/table.ts @@ -1,4 +1,5 @@ import { type Locator, type Page, expect } from "@playwright/test"; +import { waitForLoadingComplete } from "./loading.ts"; // The realm list can load slowly while parallel workers create and delete realms. const TABLE_LOAD_TIMEOUT_MS = 15_000; @@ -8,6 +9,7 @@ export async function searchItem( placeHolder: string, itemName: string, ) { + await waitForLoadingComplete(page); await page .locator("table tbody") // Use first() because some pages have multiple elements (e.g. drag-and-drop rows). @@ -15,6 +17,7 @@ export async function searchItem( .waitFor({ state: "visible", timeout: TABLE_LOAD_TIMEOUT_MS }); await page.getByPlaceholder(placeHolder).fill(itemName); await page.keyboard.press("Enter"); + await waitForLoadingComplete(page); } export async function clearAllFilters(page: Page) { @@ -26,6 +29,7 @@ function escapeRegex(value: string) { } export async function clickTableRowItem(page: Page, itemName: string) { + await waitForLoadingComplete(page); const tableBody = page.locator("table tbody"); await tableBody // Use first() because some pages have multiple elements (e.g. drag-and-drop rows). @@ -73,6 +77,7 @@ export async function assertRowExists( itemName: string, exist = true, ) { + await waitForLoadingComplete(page); const row = page.locator("table tbody").getByRole("row", { name: itemName }); if (exist) { await expect(row.first()).toBeVisible(); @@ -111,47 +116,14 @@ export async function clickTableToolbarItem( .getByRole("button", { name: itemName, exact: true }) .or(toolbar.getByRole("link", { name: itemName, exact: true })) .first(); - try { - await exactToolbarItem.waitFor({ state: "visible", timeout: 2_000 }); - await exactToolbarItem.click(); - return; - } catch { - // Fall through to partial name and overflow menu attempts. - } - - const partialToolbarItem = toolbar - .getByRole("button", { name: itemName }) - .or(toolbar.getByRole("link", { name: itemName })) - .first(); - try { - await partialToolbarItem.waitFor({ state: "visible", timeout: 2_000 }); - await partialToolbarItem.click(); - return; - } catch { - // Fall through to overflow menu attempt. - } - - const overflowKebab = toolbar.getByTestId("kebab"); - if ((await overflowKebab.count()) > 0) { - await overflowKebab.click(); - const exactMenuItem = page.getByRole("menuitem", { - name: itemName, - exact: true, - }); - if ((await exactMenuItem.count()) > 0) { - await exactMenuItem.first().click(); - return; - } - await page.getByRole("menuitem", { name: itemName }).first().click(); - return; - } - - throw new Error(`Toolbar item "${itemName}" not found`); + await exactToolbarItem.waitFor({ state: "visible", timeout: 2_000 }); + await exactToolbarItem.click(); } export async function getTableData(page: Page, name: string) { // Retry the complete data capture so the wait and read cannot race each other // during React re-renders that momentarily empty the table. + // getTableRows already waits for loading to complete. let tableData: string[][] = []; await expect .poll( @@ -182,6 +154,7 @@ export async function assertTableRowsLength( } async function getTableRows(page: Page, name: string): Promise { + await waitForLoadingComplete(page); const table = page .getByRole("grid") .and(page.getByLabel(name, { exact: true })); @@ -245,4 +218,5 @@ export async function expandRow(page: Page, tableName: string, row: number) { export async function refreshTable(page: Page) { await page.getByTestId("refresh").click(); + await waitForLoadingComplete(page); } diff --git a/js/apps/admin-ui/test/workflows/main.spec.ts b/js/apps/admin-ui/test/workflows/main.spec.ts index 4dc17c906bc..a7f5b79367e 100644 --- a/js/apps/admin-ui/test/workflows/main.spec.ts +++ b/js/apps/admin-ui/test/workflows/main.spec.ts @@ -119,9 +119,7 @@ test.describe.serial("Workflow CRUD", () => { await expect(toggleLocator).toBeEnabled(); await expect(toggleLocator).toBeChecked(); - // Force click (ignores actionability—best for flaky React toggles) - // Without this, test fails intermittently waiting for the element to be actionable - await toggleLocator.click({ force: true, timeout: 5000 }); + await toggleLocator.click(); await assertNotificationMessage(page, workflowDisabledMessage); await expect(toggleLocator).not.toBeChecked(); diff --git a/js/libs/ui-shared/src/buttons/FormSubmitButton.tsx b/js/libs/ui-shared/src/buttons/FormSubmitButton.tsx index 7976c5ccd2b..e51a6adb42d 100644 --- a/js/libs/ui-shared/src/buttons/FormSubmitButton.tsx +++ b/js/libs/ui-shared/src/buttons/FormSubmitButton.tsx @@ -34,6 +34,7 @@ export const FormSubmitButton = ({ return ( ,