diff --git a/.github/files/e2e-tests/e2e-matrix.js b/.github/files/e2e-tests/e2e-matrix.js index aad3dcca7347..52757ad50502 100644 --- a/.github/files/e2e-tests/e2e-matrix.js +++ b/.github/files/e2e-tests/e2e-matrix.js @@ -37,6 +37,48 @@ const projects = [ targets: [ 'plugins/jetpack', 'packages/comments' ], buildGroup: 'jetpack-core', }, + { + project: 'Jetpack admin shell', + path: 'projects/plugins/jetpack/tests/e2e', + testScript: 'test:admin-shell:ci', + testArgs: [], + targets: [ 'plugins/jetpack' ], + buildGroup: 'jetpack-core', + // On pull requests: WordPress latest only, and only the @smoke tests unless the PR itself changes one of these projects or files. + pullRequest: { + wpVersions: [ 'latest' ], + browsers: 'chromium', + fullSuiteFor: [ + 'packages/admin-ui', + 'packages/my-jetpack', + 'packages/jitm', + 'packages/forms', + 'packages/podcast', + 'packages/protect', + 'packages/search', + 'packages/backup', + 'packages/activity-log', + 'packages/publicize', + 'packages/newsletter', + 'packages/seo', + 'packages/videopress', + 'packages/monetize', + 'packages/premium-analytics', + // The shell imports its view transitions. + 'packages/wp-build-polyfills', + ], + // The suite itself, and its CI files (when the PR also reaches the plugin). + fullSuiteForFiles: new RegExp( + [ + '^projects/plugins/jetpack/tests/e2e/(specs/admin-shell/|helpers/admin-shell|plugins/e2e-admin-shell|bin/admin-shell|playwright\\.admin-shell)', + '^\\.github/(workflows/e2e-tests\\.yml|files/e2e-tests/)', + ].join( '|' ) + ), + }, + // On pushes to the mirror's trunk. The scheduled run covers the other browsers and WordPress version. + mirrorTrunk: { wpVersions: [ 'latest' ], browsers: 'chromium' }, + scheduled: true, + }, { project: 'Jetpack sync', path: 'projects/plugins/jetpack/tests/e2e', @@ -174,6 +216,44 @@ function minWpVersion() { const matrix = []; +/** + * The pull request's diff range, for `git diff`. + * + * @return {string} `base...head`. + */ +function pullRequestDiff() { + const event = JSON.parse( fs.readFileSync( process.env.GITHUB_EVENT_PATH, 'utf8' ) ); + return `${ event.pull_request.base.sha }...${ event.pull_request.head.sha }`; +} + +/** + * Files the pull request changes. + * + * @return {string[]} Paths from the repository root. + */ +function changedFiles() { + return execSync( `git diff --name-only ${ pullRequestDiff() }` ) + .toString() + .split( '\n' ) + .filter( Boolean ); +} + +/** + * Projects the pull request changes itself, without the projects that only depend on them. + * + * @return {Set} Project slugs, e.g. 'packages/admin-ui'. + */ +function directlyChangedProjects() { + const diff = pullRequestDiff(); + return new Set( + // `--extra=e2e`: a change to the e2e environment counts as a change to every project. + execSync( `pnpm jetpack dependencies list --extra=e2e --git-changed=${ diff }` ) + .toString() + .split( '\n' ) + .filter( Boolean ) + ); +} + /** * Queue a project against both the latest WordPress release and the oldest one we still support, * so a change that only breaks the minimum version is caught while it's still in review. @@ -210,8 +290,20 @@ switch ( process.env.GITHUB_EVENT_NAME ) { } const targets = dependencyCache.get( command ); - if ( Object.keys( changedProjects ).some( target => targets.includes( target ) ) ) { + if ( ! Object.keys( changedProjects ).some( target => targets.includes( target ) ) ) { + continue; + } + if ( ! project.pullRequest || process.env.GITHUB_EVENT_NAME !== 'pull_request' ) { pushBothVersions( project ); + continue; + } + const { wpVersions, browsers, fullSuiteFor, fullSuiteForFiles } = project.pullRequest; + const direct = directlyChangedProjects(); + const smoke = + ! fullSuiteFor.some( slug => direct.has( slug ) ) && + ! changedFiles().some( file => fullSuiteForFiles.test( file ) ); + for ( const wpVersion of wpVersions ) { + matrix.push( { ...project, wpVersion, browsers, smoke } ); } } break; @@ -239,17 +331,32 @@ switch ( process.env.GITHUB_EVENT_NAME ) { } break; } + case 'schedule': + for ( const project of projects.filter( ( { scheduled } ) => scheduled ) ) { + pushBothVersions( project ); + } + break; case 'repository_dispatch': if ( process.env.DISPATCH_REPO ) { const repoName = process.env.DISPATCH_REPO.split( '/' )[ 1 ]; + const isTrunk = + process.env.DISPATCH_REF_TYPE === 'branch' && process.env.DISPATCH_REF_NAME === 'trunk'; for ( const project of projects ) { const packageJson = JSON.parse( fs.readFileSync( `${ project.path }/package.json`, 'utf8' ) ); - if ( packageJson?.ci?.mirrorName === repoName ) { + if ( packageJson?.ci?.mirrorName !== repoName ) { + continue; + } + if ( ! isTrunk || ! project.mirrorTrunk ) { pushBothVersions( project ); + continue; + } + const { wpVersions, browsers } = project.mirrorTrunk; + for ( const wpVersion of wpVersions ) { + matrix.push( { ...project, wpVersion, browsers } ); } } } else { @@ -260,4 +367,7 @@ switch ( process.env.GITHUB_EVENT_NAME ) { console.error( `Unsupported GITHUB_EVENT_NAME ${ process.env.GITHUB_EVENT_NAME }.` ); } -console.log( JSON.stringify( matrix ) ); +// These are input for this script, not for the workflow. +console.log( + JSON.stringify( matrix.map( ( { pullRequest, mirrorTrunk, scheduled, ...entry } ) => entry ) ) +); diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index e3fcaa7be708..0ca9b225b297 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -7,6 +7,9 @@ on: - '**/changelog/**' repository_dispatch: types: [ 'e2e tests**' ] + schedule: + # Daily, for the projects marked `scheduled` in e2e-matrix.js. + - cron: '43 4 * * *' workflow_dispatch: inputs: wp_version: @@ -16,6 +19,7 @@ on: concurrency: # wp_version keeps concurrent dispatches for different WordPress versions from cancelling each other. + # The event name keeps pushes, which arrive as repository_dispatch, from cancelling scheduled runs. group: e2e-tests-${{ github.event_name }}-${{ github.ref }}-${{ case( github.event_name == 'repository_dispatch', github.event.action, '' ) }}-${{ inputs.wp_version }} cancel-in-progress: true @@ -35,7 +39,9 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 # 2025-11-20: The pnpm install may take a few minutes on cache miss. # Only run tests in the main repository - if: github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name + if: > + github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && + ( github.event_name != 'schedule' || github.repository == 'Automattic/jetpack' ) outputs: matrix: ${{ steps.evaluate.outputs.matrix }} build-matrix: ${{ steps.evaluate.outputs.build-matrix }} @@ -61,6 +67,8 @@ jobs: id: evaluate env: DISPATCH_REPO: ${{ github.event.client_payload.repository }} + DISPATCH_REF_NAME: ${{ github.event.client_payload.ref_name }} + DISPATCH_REF_TYPE: ${{ github.event.client_payload.ref_type }} WP_VERSION: ${{ inputs.wp_version }} run: | MATRIX="$(node .github/files/e2e-tests/e2e-matrix.js)" @@ -165,6 +173,8 @@ jobs: # Used in tests for enhanced reporting of global projects. The WordPress version is part of the # name so the two runs of a project are distinguishable in the report. PROJECT_NAME: '${{ matrix.project }} WP ${{ matrix.wpVersion }}' + # Admin shell suite: every browser, unless e2e-matrix.js narrows it. + ADMIN_SHELL_BROWSERS: ${{ matrix.browsers || 'chromium,firefox,webkit' }} strategy: fail-fast: false matrix: @@ -270,9 +280,12 @@ jobs: working-directory: ${{ matrix.path }} env: JSON_ARGS: ${{ toJSON(matrix.testArgs) }} + TEST_SCRIPT: ${{ matrix.testScript || 'test:run' }} + # Set by e2e-matrix.js on pull requests that don't change the admin shell or a dashboard it switches to. + ADMIN_SHELL_SMOKE: ${{ case( matrix.smoke == true, '1', '' ) }} run: | mapfile -t TEST_ARGS < <(jq -r '.[]' <<<"$JSON_ARGS") - pnpm run test:run "${TEST_ARGS[@]}" + pnpm run "$TEST_SCRIPT" "${TEST_ARGS[@]}" - name: Test environment tear-down if: ${{ always() }} @@ -341,9 +354,14 @@ jobs: actions: read # actions/checkout, actions/download-artifact contents: read - # Only mirror-repo dispatches notify. PR feedback is already in the GitHub Checks UI, and a manual - # dispatch has a human watching it who doesn't need the channel told. - if: ${{ always() && needs.e2e-tests.result != 'cancelled' && github.event_name == 'repository_dispatch' }} + # Only mirror-repo dispatches and scheduled runs notify. PR feedback is already in the GitHub Checks UI, + # and a manual dispatch has a human watching it who doesn't need the channel told. + # A timed-out job counts as cancelled. No push replaces a scheduled run, so there that's worth reporting. + if: > + always() && ( + github.event_name == 'repository_dispatch' && needs.e2e-tests.result != 'cancelled' || + github.event_name == 'schedule' && github.repository == 'Automattic/jetpack' + ) needs: [e2e-tests] steps: diff --git a/projects/packages/admin-ui/changelog/fix-admin-shell-announce-after-modal b/projects/packages/admin-ui/changelog/fix-admin-shell-announce-after-modal new file mode 100644 index 000000000000..4e9c4d27fe79 --- /dev/null +++ b/projects/packages/admin-ui/changelog/fix-admin-shell-announce-after-modal @@ -0,0 +1,4 @@ +Significance: patch +Type: fixed + +Admin shell: Wait for a closed modal to give the page back before announcing the next page. diff --git a/projects/packages/admin-ui/src/admin-shell/overlays.js b/projects/packages/admin-ui/src/admin-shell/overlays.js index 07b077e5f8ff..48359cbc6834 100644 --- a/projects/packages/admin-ui/src/admin-shell/overlays.js +++ b/projects/packages/admin-ui/src/admin-shell/overlays.js @@ -124,11 +124,17 @@ export async function closeDialogsOf( slug ) { .flatMap( el => [ el, ...el.querySelectorAll( DIALOGS ) ] ) .filter( el => el.matches( DIALOGS ) ); dialogs.filter( d => ! escaped.has( d ) ).forEach( pressEscape ); + // A modal gives the document back in an effect cleanup, which can run after it has left it. + const documentHidden = () => + [ ...document.querySelectorAll( '#wpwrap, .a11y-speak-region' ) ].some( el => + el.closest( '[aria-hidden="true"]' ) + ); + const open = () => dialogs.some( d => d.isConnected ) || ( dialogs.length && documentHidden() ); const start = performance.now(); const timeout = () => dialogs.some( d => d.isConnected && d.closest( CLOSING ) ) ? EXIT_TIMEOUT : CLOSE_TIMEOUT; // Timers, not frames: a Back in a background tab gets no animation frames. - while ( dialogs.some( d => d.isConnected ) && performance.now() - start < timeout() ) { + while ( open() && performance.now() - start < timeout() ) { await new Promise( resolve => setTimeout( resolve, 16 ) ); } // One that stayed open, such as behind a confirm, gets Escape again the next time. diff --git a/projects/packages/admin-ui/tests/js/admin-shell/overlays.test.js b/projects/packages/admin-ui/tests/js/admin-shell/overlays.test.js index 7e66f7ad8a3e..a56a2ace5c4f 100644 --- a/projects/packages/admin-ui/tests/js/admin-shell/overlays.test.js +++ b/projects/packages/admin-ui/tests/js/admin-shell/overlays.test.js @@ -99,6 +99,22 @@ describe( 'overlays', () => { expect( otherModal ).toBeInTheDocument(); } ); + it( 'waits for a closed modal to give the document back', async () => { + const wrap = await addToBody( '' ); + wrap.id = 'wpwrap'; + wrap.setAttribute( 'aria-hidden', 'true' ); + const modal = await addToBody( '
' ); + modal.addEventListener( 'keydown', () => { + setTimeout( () => modal.remove(), 50 ); + // unmodalize() runs in an effect cleanup, after React has removed the modal. + setTimeout( () => wrap.removeAttribute( 'aria-hidden' ), 120 ); + } ); + + await closeDialogsOf( 'my-jetpack' ); + + expect( wrap ).not.toHaveAttribute( 'aria-hidden' ); + } ); + const animatingOut = dialog => dialog.parentElement.classList.add( 'is-animating-out' ); const endingStyle = dialog => dialog.setAttribute( 'data-ending-style', '' ); diff --git a/projects/plugins/jetpack/changelog/add-admin-shell-e2e-ci b/projects/plugins/jetpack/changelog/add-admin-shell-e2e-ci new file mode 100644 index 000000000000..f8207af1c918 --- /dev/null +++ b/projects/plugins/jetpack/changelog/add-admin-shell-e2e-ci @@ -0,0 +1,5 @@ +Significance: patch +Type: other +Comment: Run the admin shell e2e suite in CI: a smoke set on most pull requests, the full suite when the shell or a dashboard changes. + + diff --git a/projects/plugins/jetpack/tests/e2e/README.md b/projects/plugins/jetpack/tests/e2e/README.md index b0430e99fc7e..561231c7ea33 100644 --- a/projects/plugins/jetpack/tests/e2e/README.md +++ b/projects/plugins/jetpack/tests/e2e/README.md @@ -155,10 +155,25 @@ pnpm test:admin-shell - `ADMIN_SHELL_URL` (default `http://localhost:8889`) must have `jetpack_admin_shell_enabled` on. Members marked `optional` in `helpers/admin-shell-helper.ts` need site setup, noted on each entry, and tests that use one skip where the site's admin menu lacks it. SEO, for example, shows only with the `seo-admin-ui` plan feature or the `rsm_jetpack_seo` filter, and with the `seo-tools` module on. - `ADMIN_SHELL_OFF_URL` is optional: a site with the shell off, for the `shell off` smoke projects. Without it they are skipped. - `ADMIN_SHELL_STANDALONE_URL` (with `ADMIN_SHELL_STANDALONE_USER` / `ADMIN_SHELL_STANDALONE_PASSWORD`) is optional: a site with the shell on and only standalone plugins, such as Backup, Social and VideoPress, without the Jetpack plugin (JETPACK-3419). It adds the `standalone` projects; without it there are none. Run it again after installing standalone plugins built against different Admin UI versions. +- `ADMIN_SHELL_BROWSERS` (default `chromium,firefox,webkit`) is a comma-separated list of the browsers to install and run. +- `ADMIN_SHELL_SMOKE=1` runs only the tests tagged `@smoke`. +- `ADMIN_SHELL_ALONE=1` runs only the specs that change or watch site-wide state (`ALONE` in the config: `feature-off`, and the Chromium `hover side effects` project, which needs `plugins/e2e-admin-shell.php`). Without it, those specs are left out. Run them with `--workers=1`, apart from the rest. - Add `--project='shell on: chromium'` to run one browser. Tests read shell state only through `readShell()` in `helpers/admin-shell-helper.ts`, which uses the `data-shell-page` / `data-shell-state` hooks. A document without the shell (shell off, or `?jetpack_admin_shell=0`) never has those hooks, so `readShell()` reads it from the `jetpack_page_` body class and that page's mount element; keep that path after the rewrite. `switchTo()` fails if a switch reloads the document, so tests that expect a full load click `menuLink()` instead. +In CI, the `Jetpack admin shell` entry in `.github/files/e2e-tests/e2e-matrix.js` runs it on PRs that touch the Jetpack plugin or any project it depends on (which covers `admin-ui` and every member), or the suite itself. `pnpm test:admin-shell:ci` (`bin/admin-shell-ci.sh`) runs it against the Docker site from `pnpm env:up`, reading the login from the decrypted config (`pnpm config:decrypt`). It activates the Forms and Podcast modules, then the `e2e-admin-shell` plugin, which keeps the site out of offline mode, stubs a WordPress.com connection (most members need one) and fails WordPress.com requests at once, and then the AI module, which needs that connection. It runs the `ALONE` specs first, with one worker, and makes sure Forms is on again. Then it runs the shell-on projects, then sets the `e2e_admin_shell_off` option and runs the shell-off smoke, so the two runs differ only by the flag. The standalone projects don't run in CI. + +Pull requests run it in Chromium, against WordPress latest only. A pull request that changes `admin-ui`, `my-jetpack`, `jitm`, `wp-build-polyfills`, a dashboard package, the e2e environment or this suite (`fullSuiteFor` and `fullSuiteForFiles` in `e2e-matrix.js`) runs the whole suite (a change to only the e2e workflow files doesn't queue the entry at all); any other pull request that reaches the Jetpack plugin, including one that changes only its Settings or AI dashboard, runs only the tests tagged `@smoke` (`ADMIN_SHELL_SMOKE=1`). + +The full suite opens only the dashboards in `helpers/admin-shell-helper.ts` that the CI site has. Pull request, scheduled and manual runs also build only the packages in this project's `build` script. For a dashboard package that isn't in it, such as `monetize` or `premium-analytics`, these runs don't test its JavaScript. + +Every other run uses the whole suite: + +- Each push to `jetpack-production` trunk runs it in Chromium, against WordPress latest. Its release branches and tags use all three browsers, on WordPress latest and the minimum supported version. +- A daily scheduled run builds monorepo trunk (not the mirror's full production build) and runs only this suite, in all three browsers, on both WordPress versions. New pushes can't cancel it. Failures go to Slack through the same notification job as the mirror runs. +- Manual runs use all three browsers, on one WordPress version. + Known bugs are `test.fail()` with a reason, so a fix shows up as an unexpected pass: remove the marker in the same PR. Intermittent bugs can't use `test.fail()`. Wrap those tests in `intermittentSpikeBug()`, which adds the `intermittent spike bug` annotation and the only retries in the config, so they report as flaky and anything else that fails intermittently still fails. ## CI Configuration diff --git a/projects/plugins/jetpack/tests/e2e/bin/admin-shell-ci.sh b/projects/plugins/jetpack/tests/e2e/bin/admin-shell-ci.sh new file mode 100755 index 000000000000..e50f50e9b974 --- /dev/null +++ b/projects/plugins/jetpack/tests/e2e/bin/admin-shell-ci.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash + +# Runs the admin shell suite against the e2e Docker site from `pnpm env:up`: site-wide state specs, shell on, then shell off. +# Extra arguments go to every Playwright run. ADMIN_SHELL_SMOKE=1 runs only the @smoke tests. + +set -uo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1 + +WP=( pnpm jetpack docker --type e2e --name t1 wp -- ) + +ADMIN_SHELL_USER=$( node -p 'require( "./config/local.cjs" ).testSites.default.username' ) || exit 1 +ADMIN_SHELL_PASSWORD=$( node -p 'require( "./config/local.cjs" ).testSites.default.password' ) || exit 1 +export ADMIN_SHELL_USER ADMIN_SHELL_PASSWORD +# The shell-off run points ADMIN_SHELL_OFF_URL at the same site; this matches the config's default. +SITE_URL=${ADMIN_SHELL_URL:-http://localhost:8889} + +# Comma-separated; playwright.admin-shell.config.ts runs the same list. +IFS=, read -ra BROWSERS <<<"${ADMIN_SHELL_BROWSERS:-chromium,firefox,webkit}" +# The runner image already has what Chromium needs; Firefox and WebKit need system packages. +if [[ "${BROWSERS[*]}" == chromium ]]; then + playwright install chromium || exit 1 +else + playwright install --with-deps "${BROWSERS[@]}" || exit 1 +fi + +# The site is never connected, so default modules (including the Forms and Podcast members) aren't auto-activated. +# Do this before e2e-admin-shell takes the site out of offline mode, where an unconnected site refuses activation. +for module in contact-form podcast; do + "${WP[@]}" jetpack module activate "$module" || exit 1 +done + +STATUS=0 +# A 4-core runner: the browsers and the site share it. +export PLAYWRIGHT_WORKERS=${PLAYWRIGHT_WORKERS:-4} + +echo "::group::Shell on" +"${WP[@]}" plugin activate e2e-admin-shell || exit 1 +# Jetpack AI's sidebar item shows only with the ai module on, and it needs the stubbed connection to activate. +"${WP[@]}" jetpack module activate ai || exit 1 +"${WP[@]}" option delete e2e_admin_shell_off >/dev/null 2>&1 +# The specs that need the site to themselves (ALONE in the config), first and one at a time. +if [[ "${ADMIN_SHELL_SMOKE:-}" != 1 ]]; then + ALONE_PROJECTS=( --project='shell on: *' ) + # The config defines the hover project only for Chromium. + [[ " ${BROWSERS[*]} " == *" chromium "* ]] && ALONE_PROJECTS+=( --project='hover side effects' ) + ADMIN_SHELL_RUN=alone ADMIN_SHELL_ALONE=1 PLAYWRIGHT_WORKERS=1 \ + playwright test -c playwright.admin-shell.config.ts "${ALONE_PROJECTS[@]}" "$@" || STATUS=1 + # feature-off switches Forms off. If its cleanup failed, every later Forms test would fail too. + "${WP[@]}" jetpack module activate contact-form || exit 1 +fi +ADMIN_SHELL_RUN=shell-on playwright test -c playwright.admin-shell.config.ts --project='shell on: *' "$@" || STATUS=1 +echo "::endgroup::" + +echo "::group::Shell off" +"${WP[@]}" option update e2e_admin_shell_off 1 || exit 1 +# One worker: both logins run here, and two at once on one site can stall each other. +ADMIN_SHELL_RUN=shell-off PLAYWRIGHT_WORKERS=1 ADMIN_SHELL_OFF_URL="$SITE_URL" \ + ADMIN_SHELL_OFF_USER="$ADMIN_SHELL_USER" ADMIN_SHELL_OFF_PASSWORD="$ADMIN_SHELL_PASSWORD" \ + playwright test -c playwright.admin-shell.config.ts --project='shell off: *' "$@" || STATUS=1 +echo "::endgroup::" + +exit $STATUS diff --git a/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-a11y-helper.ts b/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-a11y-helper.ts index 6558e9681410..9f219caeb1e9 100644 --- a/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-a11y-helper.ts +++ b/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-a11y-helper.ts @@ -136,17 +136,19 @@ export function placeholderSightings( page: Page ): Promise< PlaceholderSighting } /** - * Whether this browser has saved `slug`'s header: the shell shows a stand-in only for a saved one. + * Whether this tab has saved `slug`'s own header. * * @param page - Page under test. * @param slug - Member page slug. - * @return True once the header is in local storage. + * @return True once the header is in session storage. */ export function hasSavedHeader( page: Page, slug: string ): Promise< boolean > { return page.evaluate( s => - Object.keys( localStorage ).some( - key => key.startsWith( 'jetpack-admin-shell-header:' ) && key.endsWith( `:${ s }` ) + Object.keys( sessionStorage ).some( + key => + key.startsWith( 'jetpack-admin-shell-header:' ) && + !! JSON.parse( sessionStorage.getItem( key ) ?? '{}' ).pages?.[ s ] ), slug ); diff --git a/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-helper.ts b/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-helper.ts index 431228424fc8..5f842988ca29 100644 --- a/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-helper.ts +++ b/projects/plugins/jetpack/tests/e2e/helpers/admin-shell-helper.ts @@ -20,8 +20,8 @@ export interface Member { mountId: string; /** `document.title` up to ` ‹`, as a full page load sets it. */ title: string; - /** Visible header text that proves the app rendered. */ - heading: string; + /** Visible header text that proves the app rendered: exact as a string, a match as a RegExp. */ + heading: string | RegExp; /** `search + hash` a fresh load lands on with the shell off. */ landing: RegExp; /** Needs site setup; tests that use it skip on a site whose admin menu lacks it. */ @@ -44,6 +44,28 @@ export const MEMBERS: Member[] = [ heading: 'Forms', landing: /^\?page=jetpack-forms-responses-wp-admin&p=%2Fforms$/, }, + { + slug: 'jetpack-ai', + mountId: 'jetpack-ai-hub-wp-admin-app', + title: 'Jetpack AI', + heading: /Jetpack AI/, + landing: /^\?page=jetpack-ai(&p=%2F[^#&]*)?$/, + }, + { + slug: 'jetpack-settings', + mountId: 'jetpack-settings-dashboard-wp-admin-app', + title: 'Settings', + heading: /Settings/, + // Settings routes with a HashRouter. + landing: /^\?page=jetpack-settings(#\/[\w-]*)?$/, + }, + { + slug: 'jetpack-podcast', + mountId: 'jetpack-podcast-dashboard-wp-admin-app', + title: 'Podcast', + heading: /Podcast/, + landing: /^\?page=jetpack-podcast(&p=%2F[^#&]*)?$/, + }, { slug: 'jetpack-seo', mountId: 'jetpack-seo-dashboard-wp-admin-app', @@ -62,6 +84,8 @@ export const MEMBERS: Member[] = [ // Needs the Boost plugin. optional: true, }, + /* Activity Log, Newsletter, Protect and VideoPress are members too, but CI leaves their modules off, + * and its stubbed WordPress.com connection can't fetch the data their pages show. */ ]; export const member = ( slug: string ): Member => { @@ -273,16 +297,67 @@ function shellProbe( mountIds: Record< string, string > ) { }; } +/** + * Log in through the wp-login.php of `page`'s base URL. + * + * @param page - Page to log in with. + * @param user - Username. + * @param password - Password. + */ +export async function submitLogin( page: Page, user: string, password: string ): Promise< void > { + await page.goto( '/wp-login.php' ); + // Jetpack SSO can put the WordPress.com button first. + const toggle = page.getByText( 'Log in with username and password' ); + if ( await toggle.isVisible().catch( () => false ) ) { + await toggle.click(); + } + /* wp-login.php focuses a field 200 ms after load, and empties the password first when the username + * comes prefilled, as it does for a context that is already logged in. Fill only after that runs. */ + await page + .waitForFunction( + () => !! document.querySelector( '#user_login:focus, #user_pass:focus' ), + null, + { timeout: 5000 } + ) + .catch( () => undefined ); + await expect( async () => { + await page.locator( '#user_login' ).fill( user ); + await page.locator( '#user_pass' ).fill( password ); + await expect( page.locator( '#user_login' ) ).toHaveValue( user, { timeout: 1000 } ); + await expect( page.locator( '#user_pass' ) ).toHaveValue( password, { timeout: 1000 } ); + } ).toPass( { timeout: 15000 } ); + await page.locator( '#wp-submit' ).click(); + await expect( page.locator( '#wpadminbar' ) ).toBeVisible( { timeout: 60000 } ); +} + +const pageErrors = new WeakMap< Page, string[] >(); + /** * Install the shell probe. Call before the first navigation. * * @param page - Page under test. */ export async function installShellProbe( page: Page ): Promise< void > { + const errors: string[] = []; + pageErrors.set( page, errors ); + page.on( 'pageerror', error => errors.push( error.message ) ); + page.on( 'console', message => { + if ( message.type() === 'error' ) { + errors.push( message.text() ); + } + } ); await page.addInitScript( shellProbe, Object.fromEntries( MEMBERS.map( m => [ m.slug, m.mountId ] ) ) ); + // Admin bar hover menus can open over the Jetpack submenu and swallow sidebar clicks; they aren't under test. + await page.addInitScript( () => { + document.addEventListener( 'DOMContentLoaded', () => { + const style = document.createElement( 'style' ); + style.textContent = '#wpadminbar .ab-sub-wrapper { display: none !important; }'; + document.head.append( style ); + } ); + } ); } /** @@ -331,7 +406,28 @@ export async function waitForShown( page: Page, slug: string ): Promise< void > export async function openMember( page: Page, slug: string, suffix = '' ): Promise< void > { await page.goto( `/wp-admin/admin.php?page=${ slug }${ suffix }` ); await waitForShown( page, slug ); - await expect.poll( () => isShellActive( page ), 'the shell runs on this document' ).toBe( true ); + const active = await expect + .poll( () => isShellActive( page ) ) + .toBe( true ) + .then( + () => true, + () => false + ); + if ( ! active ) { + // Say why, since every shell-on test fails here alike. + const assets = await page.evaluate( () => ( { + config: !! document.getElementById( 'wp-script-module-data-@automattic/jetpack-admin-shell' ), + client: + document.querySelector< HTMLScriptElement >( 'script[type="module"][src*="admin-shell"]' ) + ?.src ?? null, + } ) ); + throw new Error( + `The shell doesn't run on ${ slug }: ${ JSON.stringify( { + ...assets, + errors: pageErrors.get( page ) ?? [], + } ) }` + ); + } } /** @@ -449,6 +545,56 @@ export async function settle( page: Page, ms: number ): Promise< void > { await page.waitForTimeout( ms ); } +/** + * Wait until the page has gone `quietMs` with no DOM change and no request in flight, or `maxMs` passes. + * + * @param page - Page under test. + * @param maxMs - Longest wait, as a fixed settle would use. + * @param quietMs - Quiet time that counts as settled. + */ +export async function waitForQuiet( page: Page, maxMs: number, quietMs = 1000 ): Promise< void > { + const inFlight = new Set< Request >(); + let lastNetwork = Date.now(); + const started = ( request: Request ) => { + inFlight.add( request ); + lastNetwork = Date.now(); + }; + const ended = ( request: Request ) => { + inFlight.delete( request ); + lastNetwork = Date.now(); + }; + page.on( 'request', started ); + page.on( 'requestfinished', ended ); + page.on( 'requestfailed', ended ); + try { + await page.evaluate( () => { + const w = window as unknown as { __jpLastMutation?: number }; + w.__jpLastMutation = Date.now(); + new MutationObserver( () => ( w.__jpLastMutation = Date.now() ) ).observe( document, { + subtree: true, + childList: true, + attributes: true, + characterData: true, + } ); + } ); + const deadline = Date.now() + maxMs; + while ( Date.now() < deadline ) { + const lastMutation = await page.evaluate( + () => ( window as unknown as { __jpLastMutation: number } ).__jpLastMutation + ); + const now = Date.now(); + if ( ! inFlight.size && now - lastNetwork >= quietMs && now - lastMutation >= quietMs ) { + return; + } + await settle( page, 250 ); + } + } finally { + page.off( 'request', started ); + page.off( 'requestfinished', ended ); + page.off( 'requestfailed', ended ); + } +} + /** * `search + hash` of the current URL. * @@ -483,7 +629,7 @@ export async function expectShown( expect( new URL( page.url() ).searchParams.get( 'page' ) ).toBe( slug ); await expect( page - .getByRole( 'heading', { name: m.heading, exact: true } ) + .getByRole( 'heading', { name: m.heading, exact: typeof m.heading === 'string' } ) .filter( { visible: true } ) .first() ).toBeVisible(); diff --git a/projects/plugins/jetpack/tests/e2e/package.json b/projects/plugins/jetpack/tests/e2e/package.json index ab245c4862d9..1dcc8fb055fa 100644 --- a/projects/plugins/jetpack/tests/e2e/package.json +++ b/projects/plugins/jetpack/tests/e2e/package.json @@ -2,7 +2,7 @@ "private": true, "type": "module", "scripts": { - "build": "pnpm jetpack build packages/my-jetpack js-packages/social-logos js-packages/boost-score-api js-packages/components js-packages/number-formatters js-packages/charts js-packages/social-previews packages/wp-build-polyfills packages/forms packages/comments packages/assets packages/connection packages/publicize packages/blaze js-packages/ai-client plugins/jetpack -v --no-pnpm-install --production", + "build": "pnpm jetpack build packages/my-jetpack js-packages/social-logos js-packages/boost-score-api js-packages/components js-packages/number-formatters js-packages/charts js-packages/social-previews packages/admin-ui packages/wp-build-polyfills packages/forms packages/podcast packages/comments packages/assets packages/connection packages/publicize packages/blaze js-packages/ai-client plugins/jetpack -v --no-pnpm-install --production", "clean": "rm -rf output", "config:decrypt": "pnpm test-decrypt-default-config && pnpm test-decrypt-config", "distclean": "rm -rf node_modules", @@ -11,7 +11,8 @@ "env:new": "e2e-env new", "env:reset": "e2e-env reset", "env:up": "e2e-env start", - "test:admin-shell": "playwright install chromium firefox webkit && playwright test -c playwright.admin-shell.config.ts", + "test:admin-shell": "playwright install $(echo \"${ADMIN_SHELL_BROWSERS:-chromium,firefox,webkit}\" | tr , ' ') && playwright test -c playwright.admin-shell.config.ts", + "test:admin-shell:ci": "pnpm run clean && bin/admin-shell-ci.sh", "pretest:run": "pnpm run clean", "test:run": "playwright install chromium && NODE_CONFIG_DIR='./config' NODE_PATH=\"$PWD/node_modules\" playwright test", "test-decrypt-all-config": "pnpm test-decrypt-default-config && pnpm test-decrypt-config", diff --git a/projects/plugins/jetpack/tests/e2e/playwright.admin-shell.config.ts b/projects/plugins/jetpack/tests/e2e/playwright.admin-shell.config.ts index 9feb36387d58..9fd991b12de5 100644 --- a/projects/plugins/jetpack/tests/e2e/playwright.admin-shell.config.ts +++ b/projects/plugins/jetpack/tests/e2e/playwright.admin-shell.config.ts @@ -1,4 +1,4 @@ -import { defineConfig, devices } from '@playwright/test'; +import { defineConfig, devices, type ReporterDescription } from '@playwright/test'; import { STATE_OFF, STATE_ON, STATE_STANDALONE } from './helpers/admin-shell-helper'; /* @@ -9,22 +9,59 @@ const onUrl = process.env.ADMIN_SHELL_URL ?? 'http://localhost:8889'; const offUrl = process.env.ADMIN_SHELL_OFF_URL; const standaloneUrl = process.env.ADMIN_SHELL_STANDALONE_URL; const stateDir = 'output/admin-shell'; +// Separate runs against one site (shell on, then off) each need their own results. +const runDir = process.env.ADMIN_SHELL_RUN + ? `${ stateDir }/${ process.env.ADMIN_SHELL_RUN }` + : stateDir; +const reporter: ReporterDescription[] = [ + [ 'list' ], + [ 'json', { outputFile: `${ runDir }/summary.json` } ], +]; +// Same CI reporters as tools/e2e-commons/playwright.config.default.ts: the shared CTRF report and PR annotations. +if ( process.env.CI ) { + reporter.push( + [ + 'playwright-ctrf-json-reporter', + { + outputDir: runDir, + outputFile: `ctrf-report-${ Date.now() }.json`, + branchName: process.env.GITHUB_REF_NAME || '', + commit: process.env.GITHUB_SHA || '', + appName: 'jetpack', + repositoryName: process.env.GITHUB_REPOSITORY || '', + }, + ], + [ 'github' ] + ); +} + +// ADMIN_SHELL_BROWSERS (comma-separated) picks the browsers; bin/admin-shell-ci.sh installs the same list. +const browserNames = ( process.env.ADMIN_SHELL_BROWSERS || 'chromium,firefox,webkit' ).split( ',' ); const browsers = [ { name: 'chromium', use: devices[ 'Desktop Chrome' ] }, { name: 'firefox', use: devices[ 'Desktop Firefox' ] }, { name: 'webkit', use: devices[ 'Desktop Safari' ] }, -]; +].filter( browser => browserNames.includes( browser.name ) ); + +// ADMIN_SHELL_SMOKE=1 runs only the tests tagged @smoke; the login setup always runs. +const smoke = process.env.ADMIN_SHELL_SMOKE === '1' ? { grep: /@smoke/ } : {}; + +/* Specs that change or watch site-wide state, so they need the site to themselves. They run only with + * ADMIN_SHELL_ALONE=1, which bin/admin-shell-ci.sh sets for a one-worker run of their own. */ +const ALONE = [ 'feature-off.test.ts', 'hover-side-effects.test.ts' ]; +const alone = process.env.ADMIN_SHELL_ALONE === '1'; export default defineConfig( { testDir: './specs/admin-shell', - outputDir: `${ stateDir }/results`, + outputDir: `${ runDir }/results`, timeout: 180000, expect: { timeout: 20000 }, // Only login and tests wrapped in intermittentSpikeBug() retry; any other flake fails the run. retries: 0, + fullyParallel: true, workers: Number( process.env.PLAYWRIGHT_WORKERS ) || 2, - reporter: [ [ 'list' ], [ 'json', { outputFile: `${ stateDir }/summary.json` } ] ], + reporter, use: { viewport: { width: 1280, height: 1600 }, ignoreHTTPSErrors: true, @@ -51,8 +88,13 @@ export default defineConfig( { }, ...browsers.map( browser => ( { name: `shell on: ${ browser.name }`, - testIgnore: [ 'auth.setup.ts', 'shell-off.test.ts', 'standalone.test.ts' ], + ...( alone + ? { testMatch: 'feature-off.test.ts' } + : { + testIgnore: [ 'auth.setup.ts', 'shell-off.test.ts', 'standalone.test.ts', ...ALONE ], + } ), dependencies: [ 'admin shell login' ], + ...smoke, use: { ...browser.use, viewport: { width: 1280, height: 1600 }, @@ -60,10 +102,27 @@ export default defineConfig( { storageState: STATE_ON, }, } ) ), + // Chromium only: it checks the server, not the browser. + ...( alone && browserNames.includes( 'chromium' ) + ? [ + { + name: 'hover side effects', + testMatch: 'hover-side-effects.test.ts', + dependencies: [ 'admin shell login' ], + use: { + ...devices[ 'Desktop Chrome' ], + viewport: { width: 1280, height: 1600 }, + baseURL: onUrl, + storageState: STATE_ON, + }, + }, + ] + : [] ), ...browsers.map( browser => ( { name: `shell off: ${ browser.name }`, testMatch: 'shell-off.test.ts', dependencies: [ 'admin shell login' ], + ...smoke, use: { ...browser.use, viewport: { width: 1280, height: 1600 }, diff --git a/projects/plugins/jetpack/tests/e2e/plugins/e2e-admin-shell.php b/projects/plugins/jetpack/tests/e2e/plugins/e2e-admin-shell.php new file mode 100644 index 000000000000..ca6b385a2683 --- /dev/null +++ b/projects/plugins/jetpack/tests/e2e/plugins/e2e-admin-shell.php @@ -0,0 +1,144 @@ + 'administrator', + 'orderby' => 'ID', + 'number' => 1, + 'fields' => 'ID', + ) + ); + $owner = (int) reset( $admins ); + Jetpack_Options::update_options( + array( + 'id' => 123456789, + 'blog_token' => 'e2e.blog', + 'user_tokens' => array( $owner => "e2e.user.$owner" ), + 'master_user' => $owner, + ) + ); + } +); + +register_deactivation_hook( + __FILE__, + function () { + Jetpack_Options::delete_option( array( 'id', 'blog_token', 'user_tokens', 'master_user' ) ); + delete_option( 'e2e_admin_shell_off' ); + } +); + +// The stubbed tokens can't sign requests, so fail WordPress.com calls at once instead of waiting on them. +add_filter( + 'pre_http_request', + function ( $response, $args, $url ) { + $host = (string) wp_parse_url( $url, PHP_URL_HOST ); + if ( preg_match( '/(^|\.)(wordpress|wp)\.com$/', $host ) ) { // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText -- Hostname pattern. + return new WP_Error( 'e2e_admin_shell_offline', 'WordPress.com is unreachable from the admin shell e2e site.' ); + } + return $response; + }, + 10, + 3 +); + +/* + * A menu hover fetches the hovered dashboard's guest data, which must save nothing: the dashboard's own + * page load does that. Log every option and user meta write made while serving that request. + */ +const E2E_ADMIN_SHELL_GUEST_WRITES = 'e2e_admin_shell_guest_writes_'; + +// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Compared only; the shell checks the nonce. +if ( wp_doing_ajax() && isset( $_GET['action'] ) && 'jetpack_admin_shell_guest' === wp_unslash( $_GET['action'] ) ) { + $e2e_admin_shell_writes = array(); + $e2e_admin_shell_log = static function ( $key ) use ( &$e2e_admin_shell_writes ) { + // Transients are caches that expire on their own; `cron` is rescheduled by whichever request spawns cron. + if ( ! preg_match( '/^option:(_site)?_transient_/', $key ) && 'option:cron' !== $key ) { + $e2e_admin_shell_writes[] = $key; + } + }; + foreach ( array( 'added_option', 'updated_option', 'deleted_option' ) as $e2e_admin_shell_hook ) { + add_action( + $e2e_admin_shell_hook, + static function ( $option ) use ( $e2e_admin_shell_log ) { + $e2e_admin_shell_log( "option:$option" ); + } + ); + } + foreach ( array( 'added_user_meta', 'updated_user_meta', 'deleted_user_meta' ) as $e2e_admin_shell_hook ) { + add_action( + $e2e_admin_shell_hook, + static function ( $meta_id, $user_id, $meta_key ) use ( $e2e_admin_shell_log ) { + $e2e_admin_shell_log( "user_meta:$meta_key" ); + }, + 10, + 3 + ); + } + add_action( + 'shutdown', + static function () use ( &$e2e_admin_shell_writes ) { + if ( ! $e2e_admin_shell_writes ) { + return; + } + // One row per request, so parallel hovers can't overwrite each other's log. + add_option( + E2E_ADMIN_SHELL_GUEST_WRITES . wp_generate_uuid4(), + array( + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Logged only. + 'member' => isset( $_GET['member'] ) ? sanitize_key( wp_unslash( $_GET['member'] ) ) : '', + 'writes' => array_values( array_unique( $e2e_admin_shell_writes ) ), + ), + '', + false + ); + }, + PHP_INT_MAX + ); +} + +/* + * The hover test reads that log here. With `reset=1` it also clears the log and the values earlier hover + * bugs saved, so a rerun on the same site can catch them again. + */ +add_action( + 'wp_ajax_e2e_admin_shell_guest_writes', + static function () { + global $wpdb; + if ( ! current_user_can( 'manage_options' ) ) { + wp_send_json_error( null, 403, JSON_UNESCAPED_SLASHES ); + } + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Test-only lookup by prefix. + $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s", $wpdb->esc_like( E2E_ADMIN_SHELL_GUEST_WRITES ) . '%' ) ); + $log = array_map( 'get_option', $names ); + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Test-only, admins only. + if ( ! empty( $_GET['reset'] ) ) { + foreach ( $names as $name ) { + delete_option( $name ); + } + // What the Forms hover bug saved. Settings' hover writes need WordPress.com answers this site never gets. + delete_option( 'jetpack_forms_classic_state' ); + } + wp_send_json_success( $log, 200, JSON_UNESCAPED_SLASHES ); + } +); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/accessibility.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/accessibility.test.ts index 3e1136dfc14b..85fb81071858 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/accessibility.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/accessibility.test.ts @@ -19,7 +19,7 @@ import { member, openMember, readShell, - settle, + waitForQuiet, switchTo, waitForShown, withinDocument, @@ -29,7 +29,7 @@ import { const MJ = 'my-jetpack'; const FORMS = 'jetpack-forms-responses-wp-admin'; -// Widgets such as My Jetpack's stats cards render well after the heading. +// Widgets such as My Jetpack's stats cards render well after the heading; wait at most this long. const AXE_SETTLE_MS = 8000; const back = ( page: Page, slug: string ) => @@ -88,22 +88,6 @@ const ROUND_TRIP: [ string, string, Go ][] = [ ]; const STEP_NAMES = [ 'switching to Forms', 'switching back to My Jetpack', 'going Back to Forms' ]; -/** - * Walk the round trip up to step `i` and run `check` only after that step. - * - * @param page - Page under test. - * @param i - Index into `ROUND_TRIP`. - * @param check - Assertion for the last step. - * @param reset - Runs before the last step. - */ -async function walkTo( page: Page, i: number, check: Go, reset?: Go ): Promise< void > { - let step = 0; - await walk( page, ROUND_TRIP.slice( 0, i + 1 ), { - before: ( p, slug ) => ( step === i && reset ? reset( p, slug ) : Promise.resolve() ), - after: ( p, slug ) => ( step++ === i ? check( p, slug ) : Promise.resolve() ), - } ); -} - /** * Open My Jetpack, then take `steps`, checking each landed in the shell before `after` runs. * @@ -159,10 +143,13 @@ test.describe( 'Admin shell: accessibility of in-shell navigation', () => { await installA11yProbe( page ); } ); - // One test per step, so a failure names the step that lost focus. - STEP_NAMES.forEach( ( name, i ) => { - test( `focus moves to the shown page’s heading after ${ name }`, async ( { page } ) => { - await walkTo( page, i, ( p, slug ) => expect( mainHeading( p, slug ) ).toBeFocused() ); + test( 'focus moves to the shown page’s heading after each step of a round trip', async ( { + page, + } ) => { + let step = 0; + await walk( page, ROUND_TRIP, { + after: ( p, slug ) => + expect( mainHeading( p, slug ), `focus after ${ STEP_NAMES[ step++ ] }` ).toBeFocused(), } ); } ); @@ -180,22 +167,18 @@ test.describe( 'Admin shell: accessibility of in-shell navigation', () => { .toContainEqual( { politeness: 'polite', text: 'Probe check' } ); } ); - STEP_NAMES.slice( 0, 2 ).forEach( ( name, i ) => { - test( `the new page title is announced politely after ${ name }`, async ( { page } ) => { - await walkTo( - page, - i, - ( p, slug ) => - expect - .poll( () => announcements( p ), `announcement for ${ slug }` ) - .toContainEqual( - expect.objectContaining( { - politeness: 'polite', - text: expect.stringContaining( member( slug ).title ), - } ) - ), - resetA11yProbe - ); + test( 'the new page title is announced politely after each switch', async ( { page } ) => { + await walk( page, ROUND_TRIP.slice( 0, 2 ), { + before: resetA11yProbe, + after: ( p, slug ) => + expect + .poll( () => announcements( p ), `announcement for ${ slug }` ) + .toContainEqual( + expect.objectContaining( { + politeness: 'polite', + text: expect.stringContaining( member( slug ).title ), + } ) + ), } ); } ); @@ -232,7 +215,7 @@ test.describe( 'Admin shell: accessibility of in-shell navigation', () => { const baseline: Record< string, Record< string, string[] > > = {}; for ( const slug of [ FORMS, MJ ] ) { await openMember( page, slug ); - await settle( page, AXE_SETTLE_MS ); + await waitForQuiet( page, AXE_SETTLE_MS ); baseline[ slug ] = await axeViolations( page ); test.info().annotations.push( { type: 'axe on full load', @@ -240,13 +223,13 @@ test.describe( 'Admin shell: accessibility of in-shell navigation', () => { } ); } await switchTo( page, FORMS ); - await settle( page, AXE_SETTLE_MS ); + await waitForQuiet( page, AXE_SETTLE_MS ); expect( await newViolations( page, baseline[ FORMS ] ), 'new after switching to Forms' ).toEqual( {} ); await switchTo( page, MJ ); - await settle( page, AXE_SETTLE_MS ); + await waitForQuiet( page, AXE_SETTLE_MS ); expect( await newViolations( page, baseline[ MJ ] ), 'new after switching back' ).toEqual( {} ); } ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/api-fetch-nonce.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/api-fetch-nonce.test.ts index c00b1b5e8216..de3a4c24cdb2 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/api-fetch-nonce.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/api-fetch-nonce.test.ts @@ -64,32 +64,39 @@ test.describe( 'Admin shell: a stale REST nonce', () => { await installShellProbe( page ); } ); - for ( const [ first, ...switches ] of TOURS ) { - test( `refreshes once after ${ [ first, ...switches ].join( ' → ' ) }`, async ( { page } ) => { - await openMember( page, first ); - for ( const slug of switches ) { - await switchTo( page, slug ); - } - const refreshes = await routeStaleNonce( page ); + TOURS.forEach( ( [ first, ...switches ], i ) => { + // The first switch is where a guest could add a second nonce middleware. + const details = i === 1 ? { tag: '@smoke' } : {}; + + test( + `refreshes once after ${ [ first, ...switches ].join( ' → ' ) }`, + details, + async ( { page } ) => { + await openMember( page, first ); + for ( const slug of switches ) { + await switchTo( page, slug ); + } + const refreshes = await routeStaleNonce( page ); - const outcome = await page.evaluate( - ( { probe } ) => - Promise.race( [ - ( window as unknown as ApiFetchWindow ).wp - .apiFetch( { path: `/wp/v2/users/me?${ probe }=1` } ) - .then( - () => 'ok', - ( error: { code?: string } ) => `error: ${ error.code }` - ), - // Long enough for a looping page to refresh many times. - new Promise( resolve => setTimeout( () => resolve( 'timed out' ), 10000 ) ), - ] ), - { probe: PROBE } - ); - await page.unrouteAll( { behavior: 'ignoreErrors' } ); + const outcome = await page.evaluate( + ( { probe } ) => + Promise.race( [ + ( window as unknown as ApiFetchWindow ).wp + .apiFetch( { path: `/wp/v2/users/me?${ probe }=1` } ) + .then( + () => 'ok', + ( error: { code?: string } ) => `error: ${ error.code }` + ), + // Long enough for a looping page to refresh many times. + new Promise( resolve => setTimeout( () => resolve( 'timed out' ), 10000 ) ), + ] ), + { probe: PROBE } + ); + await page.unrouteAll( { behavior: 'ignoreErrors' } ); - expect( outcome, 'the retry succeeds' ).toBe( 'ok' ); - expect( refreshes(), 'nonce refreshes' ).toBe( 1 ); - } ); - } + expect( outcome, 'the retry succeeds' ).toBe( 'ok' ); + expect( refreshes(), 'nonce refreshes' ).toBe( 1 ); + } + ); + } ); } ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/auth.setup.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/auth.setup.ts index 6c769e4e3999..398b85f65a15 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/auth.setup.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/auth.setup.ts @@ -1,6 +1,11 @@ import fs from 'fs'; import { test as setup, expect, type Browser } from '@playwright/test'; -import { STATE_OFF, STATE_ON, STATE_STANDALONE } from '../../helpers/admin-shell-helper'; +import { + STATE_OFF, + STATE_ON, + STATE_STANDALONE, + submitLogin, +} from '../../helpers/admin-shell-helper'; /** * Log in through wp-login.php and save the session. @@ -18,23 +23,8 @@ async function logIn( password: string, path: string ) { - const context = await browser.newContext( { ignoreHTTPSErrors: true } ); - const page = await context.newPage(); - await page.goto( new URL( '/wp-login.php', url ).href ); - // Jetpack SSO can put the WordPress.com button first. - const toggle = page.getByText( 'Log in with username and password' ); - if ( await toggle.isVisible().catch( () => false ) ) { - await toggle.click(); - } - // wp-login.php focuses and selects the username field on a timer, which can clobber the fill. - await expect( async () => { - await page.locator( '#user_login' ).fill( user ); - await page.locator( '#user_pass' ).fill( password ); - await expect( page.locator( '#user_login' ) ).toHaveValue( user, { timeout: 1000 } ); - await expect( page.locator( '#user_pass' ) ).toHaveValue( password, { timeout: 1000 } ); - } ).toPass( { timeout: 15000 } ); - await page.locator( '#wp-submit' ).click(); - await expect( page.locator( '#wpadminbar' ) ).toBeVisible( { timeout: 60000 } ); + const context = await browser.newContext( { ignoreHTTPSErrors: true, baseURL: url } ); + await submitLogin( await context.newPage(), user, password ); await context.storageState( { path } ); await context.close(); } diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/contract.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/contract.test.ts index fca1901069fd..b8310ff73f79 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/contract.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/contract.test.ts @@ -15,32 +15,38 @@ test.describe( 'Admin shell: contract hooks and events', () => { await installShellProbe( page ); } ); - test( 'each app container carries data-shell-page and data-shell-state', async ( { page } ) => { - await openMember( page, 'my-jetpack' ); - await switchTo( page, FORMS ); - const state = await readShell( page ); - expect( state.source ).toBe( 'hooks' ); - expect( state.apps ).toEqual( { 'my-jetpack': 'hidden', [ FORMS ]: 'visible' } ); - } ); + test( + 'each app container carries data-shell-page and data-shell-state', + { tag: '@smoke' }, + async ( { page } ) => { + await openMember( page, 'my-jetpack' ); + await switchTo( page, FORMS ); + const state = await readShell( page ); + expect( state.source ).toBe( 'hooks' ); + expect( state.apps ).toEqual( { 'my-jetpack': 'hidden', [ FORMS ]: 'visible' } ); + } + ); - test( 'page-shown fires on a full load and on every switch, page-hidden on leaving', async ( { - page, - } ) => { - await openMember( page, 'my-jetpack' ); - await switchTo( page, FORMS ); - await switchTo( page, 'my-jetpack' ); - const events = await shellEvents( page ); - const shown = events - .filter( e => e.type === 'jetpack-admin-shell:page-shown' ) - .map( e => [ e.detail.page, e.detail.previous ?? null, e.detail.firstShow ] ); - expect( shown ).toEqual( [ - [ 'my-jetpack', null, true ], - [ FORMS, 'my-jetpack', true ], - [ 'my-jetpack', FORMS, false ], - ] ); - const hidden = events - .filter( e => e.type === 'jetpack-admin-shell:page-hidden' ) - .map( e => e.detail.page ); - expect( hidden ).toEqual( [ 'my-jetpack', FORMS ] ); - } ); + test( + 'page-shown fires on a full load and on every switch, page-hidden on leaving', + { tag: '@smoke' }, + async ( { page } ) => { + await openMember( page, 'my-jetpack' ); + await switchTo( page, FORMS ); + await switchTo( page, 'my-jetpack' ); + const events = await shellEvents( page ); + const shown = events + .filter( e => e.type === 'jetpack-admin-shell:page-shown' ) + .map( e => [ e.detail.page, e.detail.previous ?? null, e.detail.firstShow ] ); + expect( shown ).toEqual( [ + [ 'my-jetpack', null, true ], + [ FORMS, 'my-jetpack', true ], + [ 'my-jetpack', FORMS, false ], + ] ); + const hidden = events + .filter( e => e.type === 'jetpack-admin-shell:page-hidden' ) + .map( e => e.detail.page ); + expect( hidden ).toEqual( [ 'my-jetpack', FORMS ] ); + } + ); } ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/fallback.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/fallback.test.ts index 3a3a057e56ad..79b62bb93a01 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/fallback.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/fallback.test.ts @@ -1,13 +1,11 @@ import { test, expect } from '@playwright/test'; import { - MEMBERS, expectShown, installShellProbe, isShellActive, markDocument, menuLink, openMember, - skipUnlessOnSite, sameDocument, waitForShown, } from '../../helpers/admin-shell-helper'; @@ -19,32 +17,32 @@ test.describe( 'Admin shell: fallback', () => { await installShellProbe( page ); } ); - for ( const m of MEMBERS.filter( x => x.slug !== 'my-jetpack' ) ) { - test( `with ?jetpack_admin_shell=0, clicking ${ m.slug } is a full page load`, async ( { - page, - } ) => { - await skipUnlessOnSite( page, m.slug ); - await page.goto( '/wp-admin/admin.php?page=my-jetpack&jetpack_admin_shell=0' ); - await waitForShown( page, 'my-jetpack' ); - expect( await isShellActive( page ), 'shell is off for this request' ).toBe( false ); - await markDocument( page ); - await menuLink( page, m.slug ).click(); - await waitForShown( page, m.slug ); - expect( await sameDocument( page ), 'a new document loaded' ).toBe( false ); - } ); - } - - test( 'a failing guest endpoint still gets the user to the page', async ( { page } ) => { - let aborted = 0; - await page.route( /admin-ajax\.php\?.*action=jetpack_admin_shell_guest/, route => { - aborted++; - return route.abort(); - } ); - await openMember( page, 'my-jetpack' ); + // The shell never starts for the request, so every member link is a plain link; one is enough. + test( 'with ?jetpack_admin_shell=0, clicking Forms is a full page load', async ( { page } ) => { + await page.goto( '/wp-admin/admin.php?page=my-jetpack&jetpack_admin_shell=0' ); + await waitForShown( page, 'my-jetpack' ); + expect( await isShellActive( page ), 'shell is off for this request' ).toBe( false ); + await markDocument( page ); await menuLink( page, FORMS ).click(); await waitForShown( page, FORMS ); - expect( aborted, 'the guest endpoint was called and failed' ).toBeGreaterThan( 0 ); - await expectShown( page, FORMS ); - expect( new URL( page.url() ).searchParams.get( 'page' ) ).toBe( FORMS ); + expect( await sameDocument( page ), 'a new document loaded' ).toBe( false ); } ); + + test( + 'a failing guest endpoint still gets the user to the page', + { tag: '@smoke' }, + async ( { page } ) => { + let aborted = 0; + await page.route( /admin-ajax\.php\?.*action=jetpack_admin_shell_guest/, route => { + aborted++; + return route.abort(); + } ); + await openMember( page, 'my-jetpack' ); + await menuLink( page, FORMS ).click(); + await waitForShown( page, FORMS ); + expect( aborted, 'the guest endpoint was called and failed' ).toBeGreaterThan( 0 ); + await expectShown( page, FORMS ); + expect( new URL( page.url() ).searchParams.get( 'page' ) ).toBe( FORMS ); + } + ); } ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/feature-off.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/feature-off.test.ts index 12ea8879a073..72d54b3209e4 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/feature-off.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/feature-off.test.ts @@ -26,12 +26,13 @@ const FORMS = 'jetpack-forms-responses-wp-admin'; async function switchForms( page: Page, active: boolean ): Promise< void > { const ok = await page.evaluate( async on => { const nonce = await ( await fetch( '/wp-admin/admin-ajax.php?action=rest-nonce' ) ).text(); - const response = await fetch( '/wp-json/wpcom/v2/my-jetpack/site/features/bulk', { + // `rest_route`: the e2e site has no pretty permalinks, and there `/wp-json/` serves the home page with a 200. + const response = await fetch( '/?rest_route=/wpcom/v2/my-jetpack/site/features/bulk', { method: 'POST', headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' }, body: JSON.stringify( { active: on, modules: [ 'contact-form' ] } ), } ); - return response.ok; + return response.ok && ( response.headers.get( 'content-type' ) ?? '' ).includes( 'json' ); }, active ); expect( ok, `Forms switched ${ active ? 'on' : 'off' }` ).toBe( true ); } diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/frames.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/frames.test.ts index 1c8d51302a0c..37ccd1314b3a 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/frames.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/frames.test.ts @@ -69,7 +69,12 @@ test.describe( 'Admin shell: frame by frame', () => { } ) => { await arrive( page, from, to, visit ); const frames = await recordSwitch( page, to ); - expect( frames.length, 'frames were recorded' ).toBeGreaterThan( 10 ); + // WebKit only runs animation frames while something paints, so count frames that show the switch. + expect( + frames.some( f => f.owner === to ), + `frames were recorded through the switch: +${ summary( frames ) }` + ).toBe( true ); const notFound = frames.filter( f => f.notFound ); expect.soft( notFound, `"not found" frames:\n${ summary( notFound ) }` ).toHaveLength( 0 ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/history.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/history.test.ts index 41c0acdad048..861258b387e1 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/history.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/history.test.ts @@ -1,11 +1,9 @@ import { test, expect, type Page } from '@playwright/test'; import { - MEMBERS, expectShown, installShellProbe, menuLink, openMember, - skipUnlessOnSite, switchTo, waitForShown, where, @@ -33,21 +31,25 @@ test.describe( 'Admin shell: history', () => { await installShellProbe( page ); } ); - test( 'Back and Forward step through members one click at a time', async ( { page } ) => { - await openMember( page, 'my-jetpack' ); - const start = await historyLength( page ); - await switchTo( page, FORMS ); - await switchTo( page, 'my-jetpack' ); - expect( await historyLength( page ), 'one entry per click' ).toBe( start + 2 ); + test( + 'Back and Forward step through members one click at a time', + { tag: '@smoke' }, + async ( { page } ) => { + await openMember( page, 'my-jetpack' ); + const start = await historyLength( page ); + await switchTo( page, FORMS ); + await switchTo( page, 'my-jetpack' ); + expect( await historyLength( page ), 'one entry per click' ).toBe( start + 2 ); - await back( page, FORMS ); - await expectShown( page, FORMS ); - await back( page, 'my-jetpack' ); - expect( await where( page ) ).toMatch( /^\?page=my-jetpack/ ); - await forward( page, FORMS ); - await forward( page, 'my-jetpack' ); - await expectShown( page, 'my-jetpack' ); - } ); + await back( page, FORMS ); + await expectShown( page, FORMS ); + await back( page, 'my-jetpack' ); + expect( await where( page ) ).toMatch( /^\?page=my-jetpack/ ); + await forward( page, FORMS ); + await forward( page, 'my-jetpack' ); + await expectShown( page, 'my-jetpack' ); + } + ); /* `p` routes inside a product: each tab is a history entry, in and out of the shell. */ const tabRoutes = [ @@ -89,15 +91,6 @@ test.describe( 'Admin shell: history', () => { } ); } - for ( const m of MEMBERS ) { - test( `full load of ${ m.slug } renders with the shell on`, async ( { page } ) => { - await skipUnlessOnSite( page, m.slug ); - await openMember( page, m.slug ); - await expectShown( page, m.slug ); - expect( await where( page ) ).toMatch( m.landing ); - } ); - } - test( 'reload keeps the member that was switched to', async ( { page } ) => { await openMember( page, 'my-jetpack' ); await switchTo( page, FORMS ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/hover-side-effects.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/hover-side-effects.test.ts new file mode 100644 index 000000000000..b178b357a665 --- /dev/null +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/hover-side-effects.test.ts @@ -0,0 +1,56 @@ +import { test, expect, type Page } from '@playwright/test'; +import { MEMBERS, installShellProbe, menuLink, openMember } from '../../helpers/admin-shell-helper'; + +/* Hovering Forms used to save its classic forms state; plugins/e2e-admin-shell.php logs such writes. + * The optional members aren't on the CI site. */ +const GUESTS = MEMBERS.filter( m => m.slug !== 'my-jetpack' && ! m.optional ).map( m => m.slug ); +const LOG = '/wp-admin/admin-ajax.php?action=e2e_admin_shell_guest_writes'; + +type GuestWrites = { member: string; writes: string[] }[]; + +/** + * Option and user meta writes the shell's guest requests made, as the e2e plugin logged them. + * + * @param page - Page under test, for its session. + * @return Writes per guest request. + */ +async function guestWrites( page: Page ): Promise< GuestWrites > { + const response = await page.request.get( LOG ); + expect( response.ok(), 'the e2e plugin answers' ).toBe( true ); + return ( await response.json() ).data; +} + +test.describe( 'Admin shell: hover side effects', () => { + test.beforeEach( async ( { page } ) => { + // Enough memory that the shell prewarms every member on hover. + await page.addInitScript( () => + Object.defineProperty( Navigator.prototype, 'deviceMemory', { get: () => 8 } ) + ); + await installShellProbe( page ); + } ); + + test( 'hovering each dashboard in the menu saves nothing', async ( { page } ) => { + const reset = await page.request.get( `${ LOG }&reset=1` ); + // In CI the plugin is always on, so a failed reset there is a broken site, not a missing plugin. + test.skip( ! reset.ok() && ! process.env.CI, 'Needs the e2e-admin-shell plugin' ); + expect( reset.ok(), 'the e2e plugin resets its log' ).toBe( true ); + const fetched = new Set< string >(); + // Finished, not just answered: the plugin logs the writes as the request shuts down. + page.on( 'requestfinished', request => { + const url = new URL( request.url() ); + if ( url.searchParams.get( 'action' ) === 'jetpack_admin_shell_guest' ) { + fetched.add( url.searchParams.get( 'member' ) ?? '' ); + } + } ); + await openMember( page, 'my-jetpack' ); + + for ( const slug of GUESTS ) { + await menuLink( page, slug ).hover(); + await expect + .poll( () => fetched.has( slug ), { message: `${ slug }'s guest data was fetched` } ) + .toBe( true ); + } + + expect( await guestWrites( page ) ).toEqual( [] ); + } ); +} ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/kept-state.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/kept-state.test.ts index cc5898022e70..c7bade035c5c 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/kept-state.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/kept-state.test.ts @@ -4,6 +4,7 @@ import { menuLink, openMember, switchTo, + waitForQuiet, where, } from '../../helpers/admin-shell-helper'; @@ -53,6 +54,8 @@ test.describe( 'Admin shell: state survives a round trip', () => { test( 'scroll position survives a round trip', async ( { page } ) => { await page.setViewportSize( { width: 1280, height: 500 } ); await openMember( page, 'my-jetpack' ); + // Late cards above the fold would shift a scroll position set now (scroll anchoring). + await waitForQuiet( page, 8000 ); // Playwright scrolls a link out from under the fixed admin bar before clicking it, moving the page. const belowAdminBar = await menuLink( page, FORMS ).evaluate( a => @@ -65,8 +68,8 @@ test.describe( 'Admin shell: state survives a round trip', () => { scrolled < 100, 'My Jetpack cannot scroll far enough here with the Forms link in view' ); - await page.mouse.wheel( 0, scrolled ); - // The wheel can scroll smoothly: wait for it to land. + // A wheel can land on an inner scroller and leave the document where it was. + await page.evaluate( y => window.scrollTo( { top: y, behavior: 'instant' } ), scrolled ); await expect.poll( () => page.evaluate( () => Math.round( scrollY ) ) ).toBe( scrolled ); await page.evaluate( () => document.addEventListener( diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/leave-guard.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/leave-guard.test.ts deleted file mode 100644 index d059199fb881..000000000000 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/leave-guard.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { test, expect, type Page } from '@playwright/test'; -import { - installShellProbe, - menuLink, - openMember, - readShell, - switchTo, - withinDocument, -} from '../../helpers/admin-shell-helper'; - -const NEWSLETTER = 'jetpack-newsletter'; -const EDIT = 'Admin shell leave guard'; - -/** - * Open Newsletter's Settings tab and leave an unsaved edit in it. - * - * @param page - Page under test. - * @return The edited field. - */ -async function editNewsletterSettings( page: Page ) { - await openMember( page, 'my-jetpack' ); - test.skip( ! ( await menuLink( page, NEWSLETTER ).count() ), 'Newsletter is not on this site' ); - await switchTo( page, NEWSLETTER ); - await page.getByRole( 'tab', { name: 'Settings' } ).filter( { visible: true } ).click(); - const sender = page.getByRole( 'textbox', { name: 'Sender name' } ).filter( { visible: true } ); - await sender.fill( EDIT ); - return sender; -} - -/** - * Answer every native dialog with `answer.accept`, and record its type. - * - * @param page - Page under test. - * @return The recorded dialog types, and the answer to give the next ones. - */ -function answerDialogs( page: Page ) { - const state = { seen: [] as string[], accept: true }; - page.on( 'dialog', dialog => { - state.seen.push( dialog.type() ); - return state.accept ? dialog.accept() : dialog.dismiss(); - } ); - return state; -} - -test.describe( 'Admin shell: unsaved changes', () => { - test.beforeEach( async ( { page } ) => { - await installShellProbe( page ); - } ); - - test( 'a menu click away from unsaved Newsletter Settings keeps the edit without asking', async ( { - page, - } ) => { - const dialogs = answerDialogs( page ); - const sender = await editNewsletterSettings( page ); - - await switchTo( page, 'my-jetpack' ); - await switchTo( page, NEWSLETTER ); - await expect( sender ).toHaveValue( EDIT ); - expect( dialogs.seen ).toEqual( [] ); - } ); - - test( 'a link to another Newsletter tab asks before dropping unsaved Settings', async ( { - page, - } ) => { - const dialogs = answerDialogs( page ); - const sender = await editNewsletterSettings( page ); - await switchTo( page, 'my-jetpack' ); - dialogs.accept = false; - - // No Jetpack link targets another Newsletter tab yet; a future one would take this path. - await page.evaluate( slug => { - const a = document.createElement( 'a' ); - a.id = 'leave-guard-link'; - a.textContent = 'Newsletter subscribers'; - a.href = `admin.php?page=${ slug }&p=${ encodeURIComponent( '/?tab=subscribers' ) }`; - // Above the app's fixed header, so the click is a real one. - a.style.cssText = 'position: fixed; bottom: 0; right: 0; z-index: 100000'; - document.getElementById( 'wpbody-content' )!.append( a ); - }, NEWSLETTER ); - await withinDocument( page, 'the declined link', async () => { - await page.locator( '#leave-guard-link' ).click(); - await expect.poll( () => dialogs.seen ).toEqual( [ 'confirm' ] ); - } ); - expect( ( await readShell( page ) ).visible ).toBe( 'my-jetpack' ); - - dialogs.accept = true; - await switchTo( page, NEWSLETTER ); - await expect( sender ).toHaveValue( EDIT ); - } ); -} ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/memory.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/memory.test.ts index 83c8b7b64b94..2639482227a0 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/memory.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/memory.test.ts @@ -5,13 +5,15 @@ import { menuLink, openMember, sameDocument, - skipUnlessOnSite, switchTo, waitForShown, withinDocument, } from '../../helpers/admin-shell-helper'; const FORMS = 'jetpack-forms-responses-wp-admin'; +/* Members every CI site has, so the test runs there. */ +const AI = 'jetpack-ai'; +const PODCAST = 'jetpack-podcast'; test.describe( 'Admin shell: memory budget', () => { test.beforeEach( async ( { page } ) => { @@ -23,16 +25,15 @@ test.describe( 'Admin shell: memory budget', () => { } ); test( 'past the live-app limit, a new dashboard is a full page load', async ( { page } ) => { - await skipUnlessOnSite( page, 'jetpack-seo', 'jetpack-boost' ); await openMember( page, 'my-jetpack' ); await switchTo( page, FORMS ); - await switchTo( page, 'jetpack-seo' ); + await switchTo( page, AI ); // Live dashboards still switch in place at the limit. await switchTo( page, FORMS ); await markDocument( page ); - await menuLink( page, 'jetpack-boost' ).click(); - await waitForShown( page, 'jetpack-boost' ); + await menuLink( page, PODCAST ).click(); + await waitForShown( page, PODCAST ); expect( await sameDocument( page ), 'a new document loaded' ).toBe( false ); // The page load freed the budget. @@ -42,10 +43,9 @@ test.describe( 'Admin shell: memory budget', () => { test( 'past the live-app limit, a hidden dashboard with unsaved changes keeps the page', async ( { page, } ) => { - await skipUnlessOnSite( page, 'jetpack-seo', 'jetpack-boost' ); await openMember( page, 'my-jetpack' ); await switchTo( page, FORMS ); - await switchTo( page, 'jetpack-seo' ); + await switchTo( page, AI ); // Stands in for My Jetpack with an unsaved edit whose user chooses to stay. await page.evaluate( () => window.addEventListener( 'jetpack-admin-shell:before-leave', event => { @@ -58,13 +58,13 @@ test.describe( 'Admin shell: memory budget', () => { ); await withinDocument( page, 'the cancelled page load', async () => { - await menuLink( page, 'jetpack-boost' ).click(); + await menuLink( page, PODCAST ).click(); await expect .poll( () => page.evaluate( () => ( window as unknown as { __askedFor?: string } ).__askedFor ?? '' ) ) - .toContain( 'page=jetpack-boost' ); + .toContain( 'page=jetpack-podcast' ); } ); - expect( new URL( page.url() ).searchParams.get( 'page' ) ).toBe( 'jetpack-seo' ); + expect( new URL( page.url() ).searchParams.get( 'page' ) ).toBe( AI ); } ); } ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/navigation-matrix.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/navigation-matrix.test.ts index 7443420df70f..ae7722f16a2a 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/navigation-matrix.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/navigation-matrix.test.ts @@ -3,6 +3,7 @@ import { MEMBERS, expectShown, installShellProbe, + member, menuLink, openMember, skipUnlessOnSite, @@ -10,8 +11,12 @@ import { where, } from '../../helpers/admin-shell-helper'; -/* Every ordered pair, so each member is tested as the host and as a guest. */ -const pairs = MEMBERS.flatMap( a => MEMBERS.filter( b => b !== a ).map( b => [ a, b ] as const ) ); +/* Each member against My Jetpack, as the host and as a guest; every pair would grow quadratically. */ +const hub = member( 'my-jetpack' ); +const pairs = MEMBERS.filter( m => m !== hub ).flatMap( m => [ + [ hub, m ] as const, + [ m, hub ] as const, +] ); test.describe( 'Admin shell: navigation matrix', () => { test.beforeEach( async ( { page } ) => { @@ -19,12 +24,15 @@ test.describe( 'Admin shell: navigation matrix', () => { } ); for ( const [ a, b ] of pairs ) { - test( `${ a.slug } → ${ b.slug } → ${ a.slug }`, async ( { page } ) => { + test( `${ a.slug } → ${ b.slug } → ${ a.slug }`, { tag: '@smoke' }, async ( { page } ) => { await skipUnlessOnSite( page, a.slug, b.slug ); await openMember( page, a.slug ); await expect( menuLink( page, b.slug ), `${ b.slug } is in the menu` ).toBeAttached(); await expectShown( page, a.slug ); const leftAt = await where( page ); + expect( leftAt, `a full load of ${ a.slug } lands where it does with the shell off` ).toMatch( + a.landing + ); await switchTo( page, b.slug ); await expectShown( page, b.slug ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/nonce.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/nonce.test.ts new file mode 100644 index 000000000000..4df1beb30bb0 --- /dev/null +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/nonce.test.ts @@ -0,0 +1,74 @@ +import { test, expect, type Page } from '@playwright/test'; +import { + expectShown, + installShellProbe, + openMember, + submitLogin, + switchTo, +} from '../../helpers/admin-shell-helper'; + +/** + * Log in again in a second tab, which leaves the first tab's REST nonce stale. + * + * @param page - Page under test; its context gets the new session. + */ +async function logInAgain( page: Page ): Promise< void > { + const tab = await page.context().newPage(); + await submitLogin( + tab, + process.env.ADMIN_SHELL_USER ?? 'admin', + process.env.ADMIN_SHELL_PASSWORD ?? 'password' + ); + await tab.close(); +} + +/* JETPACK-3673: guests that print wp-api-fetch's inline script used to stack nonce middlewares. */ +test.describe( 'Admin shell: stale REST nonce', () => { + test.beforeEach( async ( { page } ) => { + await installShellProbe( page ); + } ); + + test( 'after My Jetpack → Settings → Jetpack AI, a stale nonce refreshes once', async ( { + page, + } ) => { + await openMember( page, 'my-jetpack' ); + await switchTo( page, 'jetpack-settings' ); + await switchTo( page, 'jetpack-ai' ); + await expectShown( page, 'jetpack-ai' ); + + /* Count from the new login on. Background requests can hit the stale nonce too, each refreshing it + * once, so count the probe's own tries: a stale one and one retry, not a loop. */ + let refreshes = 0; + let probeTries = 0; + page.on( 'request', request => { + if ( /admin-ajax\.php\?(.*&)?action=rest-nonce/.test( request.url() ) ) { + refreshes++; + } else if ( request.url().includes( 'e2e_nonce_probe' ) ) { + probeTries++; + } + } ); + await logInAgain( page ); + const result = await page.evaluate( async () => { + const { apiFetch } = ( + window as unknown as { + wp: { apiFetch: ( o: { path: string } ) => Promise< { id: number } > }; + } + ).wp; + // A loop never settles, so give up well before the test timeout. + const timeout = new Promise< string >( resolve => + setTimeout( () => resolve( 'still retrying after 15 s' ), 15000 ) + ); + return Promise.race( [ + apiFetch( { path: '/wp/v2/users/me?e2e_nonce_probe=1' } ).then( + user => `user ${ user.id }`, + ( error: { code?: string } ) => `failed: ${ error.code }` + ), + timeout, + ] ); + } ); + + expect( result, 'the request succeeds after the refresh' ).toMatch( /^user \d+$/ ); + expect( refreshes, 'nonce refreshes' ).toBeGreaterThan( 0 ); + expect( probeTries, 'tries of the probe request' ).toBeLessThanOrEqual( 2 ); + } ); +} ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/shell-off.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/shell-off.test.ts index 97fd07ac4863..fa29991e4190 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/shell-off.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/shell-off.test.ts @@ -21,7 +21,7 @@ test.describe( 'Admin shell off: smoke', () => { await installShellProbe( page ); } ); - test( 'every member loads and links to the next', async ( { page } ) => { + test( 'every member loads and links to the next', { tag: '@smoke' }, async ( { page } ) => { const [ first, ...rest ] = MEMBERS; await page.goto( `/wp-admin/admin.php?page=${ first.slug }` ); await waitForShown( page, first.slug ); diff --git a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/tracks.test.ts b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/tracks.test.ts index b4408607ff60..64b0caf9f846 100644 --- a/projects/plugins/jetpack/tests/e2e/specs/admin-shell/tracks.test.ts +++ b/projects/plugins/jetpack/tests/e2e/specs/admin-shell/tracks.test.ts @@ -1,33 +1,56 @@ import { test, expect, type Page } from '@playwright/test'; import { - MEMBERS, VIEW_EVENT, installShellProbe, openMember, settle, - skipUnlessOnSite, switchTo, tracksEvents, } from '../../helpers/admin-shell-helper'; const FORMS = 'jetpack-forms-responses-wp-admin'; -/* Tracks calls go out after render, so give each arrival a moment before reading. */ +/* My Jetpack is the one member that records views on the unconnected test site; Forms is the other side. */ +const MJ = 'my-jetpack'; + +/* Tracks calls go out after render: the longest to wait for one, and the quiet spell that ends a wait. */ const SETTLE = 5000; +const QUIET = 1000; /** - * View events recorded since `from` events had been seen. + * Wait until `done` holds for the view events since `from` and no event has arrived for `QUIET`, or `SETTLE` passes. * * @param page - Page under test. * @param from - Count of events already seen. + * @param done - Whether the views recorded so far are what the caller waits for. * @return New view event names. */ -async function viewsSince( page: Page, from: number ): Promise< string[] > { - return ( await tracksEvents( page ) ).slice( from ).filter( name => VIEW_EVENT.test( name ) ); +async function waitForViews( + page: Page, + from: number, + done: ( views: string[] ) => boolean = () => true +): Promise< string[] > { + const deadline = Date.now() + SETTLE; + let count = -1; + let lastArrival = Date.now(); + for (;;) { + const events = await tracksEvents( page ); + if ( events.length !== count ) { + count = events.length; + lastArrival = Date.now(); + } + const views = events.slice( from ).filter( name => VIEW_EVENT.test( name ) ); + if ( ( done( views ) && Date.now() - lastArrival >= QUIET ) || Date.now() >= deadline ) { + return views; + } + await settle( page, 250 ); + } } +const any = ( views: string[] ) => views.length > 0; + /** - * View events a full load of `slug` records, skipping the test when there are none. + * View events a full load of `slug` records. When there are none, the test fails in CI and skips elsewhere. * * @param page - Page under test. * @param slug - Member page slug. @@ -35,25 +58,29 @@ async function viewsSince( page: Page, from: number ): Promise< string[] > { */ async function fullLoadViews( page: Page, slug: string ): Promise< string[] > { await openMember( page, slug ); - await settle( page, SETTLE ); - const views = [ ...new Set( await viewsSince( page, 0 ) ) ]; - test.skip( ! views.length, `${ slug } records no page view on a full load either` ); + const views = [ ...new Set( await waitForViews( page, 0, any ) ) ]; + // The CI site always records views. Another site may not, for example with Tracks off. + test.skip( + ! views.length && ! process.env.CI, + `${ slug } records no page view on a full load either` + ); + expect( views, `${ slug } records a page view on a full load` ).not.toEqual( [] ); return views; } /** * Let earlier Tracks calls land, switch to `slug`, and return the view events recorded on arrival. * - * @param page - Page under test. - * @param slug - Member page slug. + * @param page - Page under test. + * @param slug - Member page slug. + * @param expected - View events to wait for. * @return New view event names. */ -async function viewsOnSwitch( page: Page, slug: string ): Promise< string[] > { - await settle( page, SETTLE ); +async function viewsOnSwitch( page: Page, slug: string, expected: string[] ): Promise< string[] > { + await waitForViews( page, 0 ); const seen = ( await tracksEvents( page ) ).length; await switchTo( page, slug ); - await settle( page, SETTLE ); - return viewsSince( page, seen ); + return waitForViews( page, seen, views => expected.every( name => views.includes( name ) ) ); } test.describe( 'Admin shell: Tracks page views', () => { @@ -61,51 +88,23 @@ test.describe( 'Admin shell: Tracks page views', () => { await installShellProbe( page ); } ); - for ( const m of MEMBERS ) { - const other = MEMBERS.find( x => x !== m )!.slug; - - test( `the first switch to ${ m.slug } records the page view a full load does`, async ( { - page, - } ) => { - await skipUnlessOnSite( page, m.slug ); - const expected = await fullLoadViews( page, m.slug ); - await openMember( page, other ); - expect( await viewsOnSwitch( page, m.slug ) ).toEqual( expect.arrayContaining( expected ) ); - } ); - - test( `a return switch to ${ m.slug } records the page view again`, async ( { page } ) => { - await skipUnlessOnSite( page, m.slug ); - const expected = await fullLoadViews( page, m.slug ); - await openMember( page, other ); - await switchTo( page, m.slug ); - await switchTo( page, other ); - expect( await viewsOnSwitch( page, m.slug ) ).toEqual( expect.arrayContaining( expected ) ); - } ); - } - - test( 'hidden apps record no page views while another is shown', async ( { page } ) => { + test( 'the first switch to My Jetpack records the page view a full load does', async ( { + page, + } ) => { + const expected = await fullLoadViews( page, MJ ); await openMember( page, FORMS ); - await settle( page, SETTLE ); - const formsViews = new Set( await viewsSince( page, 0 ) ); - await openMember( page, 'my-jetpack' ); - await settle( page, SETTLE ); - const own = new Set( await viewsSince( page, 0 ) ); - expect( own.size, 'the probe sees My Jetpack’s own page view' ).toBeGreaterThan( 0 ); - test.skip( - [ ...formsViews ].every( name => own.has( name ) ), - 'Forms records no view event of its own, so a leak would not show' + expect( await viewsOnSwitch( page, MJ, expected ) ).toEqual( + expect.arrayContaining( expected ) ); + } ); - // Forms' router stays mounted while hidden; My Jetpack's URL writes must not reach it. + test( 'a return switch to My Jetpack records the page view again', async ( { page } ) => { + const expected = await fullLoadViews( page, MJ ); + await openMember( page, FORMS ); + await switchTo( page, MJ ); await switchTo( page, FORMS ); - await switchTo( page, 'my-jetpack' ); - await settle( page, SETTLE ); - const seen = ( await tracksEvents( page ) ).length; - await page.getByRole( 'tab', { name: 'Features' } ).filter( { visible: true } ).click(); - await settle( page, SETTLE ); - const foreign = ( await viewsSince( page, seen ) ).filter( - name => formsViews.has( name ) && ! own.has( name ) + expect( await viewsOnSwitch( page, MJ, expected ) ).toEqual( + expect.arrayContaining( expected ) ); - expect( foreign, 'view events from apps that are not shown' ).toEqual( [] ); } ); } ); diff --git a/tools/docker/jetpack-docker-config-default.yml b/tools/docker/jetpack-docker-config-default.yml index 5421d2d39166..e4130706f767 100644 --- a/tools/docker/jetpack-docker-config-default.yml +++ b/tools/docker/jetpack-docker-config-default.yml @@ -75,6 +75,7 @@ e2e: projects/plugins/boost/tests/e2e/plugins/e2e-mock-premium-features.php: /var/www/html/wp-content/plugins/e2e-mock-premium-features.php projects/plugins/boost/tests/e2e/plugins/e2e-critical-css-force-errors.php: /var/www/html/wp-content/plugins/e2e-critical-css-force-errors.php projects/plugins/boost/tests/e2e/plugins/e2e-dashboard-jitm.php: /var/www/html/wp-content/plugins/e2e-dashboard-jitm.php + projects/plugins/jetpack/tests/e2e/plugins/e2e-admin-shell.php: /var/www/html/wp-content/plugins/e2e-admin-shell.php projects/plugins/paypal-payment-buttons/tests/e2e/plugins/e2e-paypal-feature-flag.php: /var/www/html/wp-content/plugins/e2e-paypal-feature-flag.php projects/plugins/premium-analytics/tests/e2e/plugins/e2e-premium-analytics-helper/: /var/www/html/wp-content/plugins/e2e-premium-analytics-helper/ tools/e2e-commons/plugins/e2e-search-test-helper.php: /var/www/html/wp-content/plugins/e2e-search-test-helper.php