Files
payloadcms/test/helpers/e2e/waitForPageStability.ts
Jacob Fletcher f2abc80a00 test: deflakes blocks e2e (#11640)
The blocks e2e tests were flaky due to how we conditionally render
fields as they enter the viewport. This prevented Playwright from every
reaching the target element when running
`locator.scrollIntoViewIfNeeded()`. This is especially flaky on pages
with many fields because the page size would continually grow as it was
scrolled.

To fix this there are new `scrollEntirePage` and `waitForPageStability`
helpers. Together, these will ensure that all fields are rendered and
fully loaded before we start testing. An early attempt at this was made
via `page.mouse.wheel(0, 1750)`, but this is an arbitrary pixel value
that is error prone and is not future proof.

These tests were also flaky by an attempt to trigger a form state action
before it was ready to receive events. The fix here is to disable any
buttons while the form is initializing and let Playwright wait for an
interactive state.
2025-03-11 22:49:06 -04:00

55 lines
1.8 KiB
TypeScript

import type { Page } from '@playwright/test'
/**
* Checks if the page is stable by continually polling until the page size remains constant in size and there are no loading shimmers.
* A page is considered stable if it passes this test multiple times.
* This will ensure that the page won't unexpectedly change while testing.
* @param page - Playwright page object
* @param intervalMs - Polling interval in milliseconds
* @param stableChecksRequired - Number of stable checks required to consider page stable
* @returns Promise<void>
*/
export const waitForPageStability = async ({
page,
interval = 1000,
stableChecksRequired = 3,
}: {
interval?: number
page: Page
stableChecksRequired?: number
}) => {
await page.waitForLoadState('networkidle') // Wait for network to be idle
await page.waitForFunction(
async ({ interval, stableChecksRequired }) => {
return new Promise((resolve) => {
let previousHeight = document.body.scrollHeight
let stableChecks = 0
const checkStability = () => {
const currentHeight = document.body.scrollHeight
const loadingShimmers = document.querySelectorAll('.shimmer-effect')
const pageSizeChanged = currentHeight !== previousHeight
if (!pageSizeChanged && loadingShimmers.length === 0) {
stableChecks++ // Increment stability count
} else {
stableChecks = 0 // Reset stability count if page changes
}
previousHeight = currentHeight
if (stableChecks >= stableChecksRequired) {
resolve(true) // Only resolve after multiple stable checks
} else {
setTimeout(checkStability, interval) // Poll again
}
}
checkStability()
})
},
{ interval, stableChecksRequired },
)
}