From 7d55104c9b16f5c2ba8dcfc6522ca4ed8f92e7d7 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Thu, 10 Sep 2026 18:41:28 +0200 Subject: [PATCH 1/5] Test: Migrate the six remaining repository suites to Vitest --- .../test/cursor-dom-utils.jsdom.test.ts | 33 +++---- .../{index.jsdom.test.js => index.test.js} | 22 ++--- ...invalidate-attachment-resolutions.test.js} | 5 +- .../test/item-limits.jsdom.test.tsx | 47 +++++----- .../test/item-limits.jsdom.test.tsx | 47 +++++----- .../src/breadcrumb/test/index.jsdom.test.tsx | 94 +++++++++---------- test/unit/jest.config.js | 10 +- test/unit/test-migration.json | 9 +- test/unit/vitest-policy-exceptions.json | 3 +- 9 files changed, 139 insertions(+), 131 deletions(-) rename packages/editor/src/store/utils/attach-media-in-post/test/{index.jsdom.test.js => index.test.js} (94%) rename packages/editor/src/store/utils/attach-media-in-post/test/{invalidate-attachment-resolutions.jsdom.test.js => invalidate-attachment-resolutions.test.js} (92%) diff --git a/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts b/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts index ca41dacb43fe17..145c687a1414f4 100644 --- a/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts +++ b/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts @@ -1,3 +1,4 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { getCursorPosition, getNearestVisibleBlockAncestor, @@ -16,7 +17,7 @@ const OVERLAY_RECT = { } as DOMRect; function mockRect( element: HTMLElement, rect: Partial< DOMRect > ) { - element.getBoundingClientRect = jest.fn().mockReturnValue( { + vi.spyOn( element, 'getBoundingClientRect' ).mockReturnValue( { left: 0, top: 0, right: 0, @@ -26,23 +27,23 @@ function mockRect( element: HTMLElement, rect: Partial< DOMRect > ) { x: 0, y: 0, ...rect, - } ); + } as DOMRect ); } -// jsdom performs no layout and doesn't implement Range.getBoundingClientRect -// / getClientRects at all (not even as a zero-returning stub), so any test -// that lets getOffsetPositionInBlock create and measure a real Range needs -// this polyfilled. -beforeAll( () => { - Range.prototype.getBoundingClientRect = jest.fn().mockReturnValue( { - left: 0, - top: 0, - width: 0, - height: 0, - x: 0, - y: 0, - } ); - Range.prototype.getClientRects = jest.fn().mockReturnValue( [] ); +// Supplied rectangles exercise the fallback and ancestor-selection algorithms. +// Keep native Range construction and DOM traversal, without measuring layout. +beforeEach( () => { + const createRange = document.createRange.bind( document ); + vi.spyOn( document, 'createRange' ).mockImplementation( () => + Object.assign( createRange(), { + getBoundingClientRect: () => new DOMRect(), + getClientRects: () => [], + } ) + ); +} ); + +afterEach( () => { + vi.restoreAllMocks(); } ); describe( 'cursor-dom-utils', () => { diff --git a/packages/editor/src/store/utils/attach-media-in-post/test/index.jsdom.test.js b/packages/editor/src/store/utils/attach-media-in-post/test/index.test.js similarity index 94% rename from packages/editor/src/store/utils/attach-media-in-post/test/index.jsdom.test.js rename to packages/editor/src/store/utils/attach-media-in-post/test/index.test.js index d3e4188a89c549..69485426d1ffa6 100644 --- a/packages/editor/src/store/utils/attach-media-in-post/test/index.jsdom.test.js +++ b/packages/editor/src/store/utils/attach-media-in-post/test/index.test.js @@ -1,10 +1,14 @@ +import { describe, expect, it, vi } from 'vitest'; import attachMediaInPost from '..'; -const mockInvalidate = jest.fn(); +vi.mock( '@wordpress/core-data', () => ( { store: {} } ) ); -jest.mock( '../invalidate-attachment-resolutions', () => ( { - __esModule: true, - default: ( ...args ) => mockInvalidate( ...args ), +const { mockInvalidate } = vi.hoisted( () => ( { + mockInvalidate: vi.fn(), +} ) ); + +vi.mock( '../invalidate-attachment-resolutions', () => ( { + default: mockInvalidate, } ) ); const imageBlock = ( id ) => ( { @@ -24,9 +28,9 @@ const imageBlock = ( id ) => ( { * @param {Object} [options.postType] What `getPostType` resolves to. */ function createRegistry( { media = [], postType = { viewable: true } } = {} ) { - const getEntityRecords = jest.fn().mockResolvedValue( media ); - const getPostType = jest.fn().mockResolvedValue( postType ); - const saveEntityRecord = jest.fn().mockResolvedValue( {} ); + const getEntityRecords = vi.fn().mockResolvedValue( media ); + const getPostType = vi.fn().mockResolvedValue( postType ); + const saveEntityRecord = vi.fn().mockResolvedValue( {} ); const registry = { select: () => ( {} ), @@ -45,10 +49,6 @@ function createRegistry( { media = [], postType = { viewable: true } } = {} ) { const post = ( blocks ) => ( { id: 7, type: 'post', blocks } ); describe( 'attachMediaInPost', () => { - beforeEach( () => { - jest.clearAllMocks(); - } ); - it( 'attaches media that belongs to no post', async () => { const { registry, saveEntityRecord } = createRegistry( { media: [ { id: 12, post: null } ], diff --git a/packages/editor/src/store/utils/attach-media-in-post/test/invalidate-attachment-resolutions.jsdom.test.js b/packages/editor/src/store/utils/attach-media-in-post/test/invalidate-attachment-resolutions.test.js similarity index 92% rename from packages/editor/src/store/utils/attach-media-in-post/test/invalidate-attachment-resolutions.jsdom.test.js rename to packages/editor/src/store/utils/attach-media-in-post/test/invalidate-attachment-resolutions.test.js index d9936f24f29c19..e64187eb0b93bd 100644 --- a/packages/editor/src/store/utils/attach-media-in-post/test/invalidate-attachment-resolutions.jsdom.test.js +++ b/packages/editor/src/store/utils/attach-media-in-post/test/invalidate-attachment-resolutions.test.js @@ -1,5 +1,8 @@ +import { describe, expect, it, vi } from 'vitest'; import invalidateAttachmentResolutions from '../invalidate-attachment-resolutions'; +vi.mock( '@wordpress/core-data', () => ( { store: {} } ) ); + /** * Builds a registry stub whose `getCachedResolvers().getEntityRecords` returns * the supplied map, and records the invalidations. @@ -7,7 +10,7 @@ import invalidateAttachmentResolutions from '../invalidate-attachment-resolution * @param {Map|undefined} entityRecords Cached `getEntityRecords` resolutions. */ function createRegistry( entityRecords ) { - const invalidateResolution = jest.fn(); + const invalidateResolution = vi.fn(); const registry = { select: () => ( { diff --git a/packages/grid/src/dashboard-grid/test/item-limits.jsdom.test.tsx b/packages/grid/src/dashboard-grid/test/item-limits.jsdom.test.tsx index d717af659c319d..9e6df336638f6d 100644 --- a/packages/grid/src/dashboard-grid/test/item-limits.jsdom.test.tsx +++ b/packages/grid/src/dashboard-grid/test/item-limits.jsdom.test.tsx @@ -1,3 +1,4 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, fireEvent, render } from '@testing-library/react'; import { DashboardGrid } from '..'; import type { DashboardGridLayoutItem } from '../types'; @@ -8,9 +9,6 @@ class MockResizeObserver { disconnect() {} } -let originalResizeObserver: typeof ResizeObserver; -let originalGetBoundingClientRect: typeof HTMLElement.prototype.getBoundingClientRect; - function rect( left: number, top: number, width: number, height: number ) { return { left, @@ -44,38 +42,39 @@ const ITEM_RECTS: Record< string, DOMRect > = { async function activateAndStepRight( activator: Element ) { fireEvent.keyDown( activator, { code: 'Space' } ); act( () => { - jest.runOnlyPendingTimers(); + vi.runOnlyPendingTimers(); } ); fireEvent.keyDown( activator, { code: 'ArrowRight' } ); fireEvent.keyDown( activator, { code: 'Space' } ); await act( async () => { - jest.runOnlyPendingTimers(); + vi.runOnlyPendingTimers(); } ); } beforeEach( () => { - jest.useFakeTimers(); - originalResizeObserver = global.ResizeObserver; - ( global as unknown as { ResizeObserver: unknown } ).ResizeObserver = - MockResizeObserver; - originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect; - HTMLElement.prototype.getBoundingClientRect = function () { + vi.useFakeTimers(); + vi.stubGlobal( 'ResizeObserver', MockResizeObserver ); + vi.spyOn( + HTMLElement.prototype, + 'getBoundingClientRect' + ).mockImplementation( function ( this: HTMLElement ) { // eslint-disable-next-line testing-library/no-node-access const key = this.closest( '[data-wp-grid-item-key]' )?.getAttribute( 'data-wp-grid-item-key' ); return ( key && ITEM_RECTS[ key ] ) || CONTAINER_RECT; - }; + } ); } ); afterEach( () => { - ( global as unknown as { ResizeObserver: unknown } ).ResizeObserver = - originalResizeObserver; - HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect; - jest.useRealTimers(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + vi.useRealTimers(); } ); -function renderGrid( onChangeLayout: jest.Mock ) { +function renderGrid( + onChangeLayout: ( layout: DashboardGridLayoutItem[] ) => void +) { const layout: DashboardGridLayoutItem[] = [ { key: 'a', width: 1, height: 1 }, { key: 'b', width: 1, height: 1 }, @@ -97,13 +96,16 @@ function renderGrid( onChangeLayout: jest.Mock ) { /* eslint-disable testing-library/no-container, testing-library/no-node-access */ describe( 'DashboardGrid item limits', () => { it( 'renders a stored span below the floor lifted to it', () => { - const { container } = renderGrid( jest.fn() ); - const itemA = container.querySelector( '[data-wp-grid-item-key="a"]' ); - expect( itemA ).toHaveStyle( { gridColumnEnd: 'span 2' } ); + const { container } = renderGrid( vi.fn() ); + const itemA = container.querySelector< HTMLElement >( + '[data-wp-grid-item-key="a"]' + ); + expect( itemA?.style.gridColumnEnd ).toBe( 'span 2' ); } ); it( 'resizing another tile leaves the stored span untouched', async () => { - const onChangeLayout = jest.fn(); + const onChangeLayout = + vi.fn< ( layout: DashboardGridLayoutItem[] ) => void >(); const { container } = renderGrid( onChangeLayout ); const handleB = container.querySelector( '[data-wp-grid-item-key="b"] [aria-roledescription="draggable"]' @@ -124,7 +126,8 @@ describe( 'DashboardGrid item limits', () => { } ); it( 'reordering leaves the stored span untouched', async () => { - const onChangeLayout = jest.fn(); + const onChangeLayout = + vi.fn< ( layout: DashboardGridLayoutItem[] ) => void >(); const { container } = renderGrid( onChangeLayout ); const activatorA = container.querySelector( '[data-wp-grid-item-key="a"] [aria-roledescription="sortable"]' diff --git a/packages/grid/src/dashboard-lanes/test/item-limits.jsdom.test.tsx b/packages/grid/src/dashboard-lanes/test/item-limits.jsdom.test.tsx index aa48e60655ce07..61c38d3efe9a37 100644 --- a/packages/grid/src/dashboard-lanes/test/item-limits.jsdom.test.tsx +++ b/packages/grid/src/dashboard-lanes/test/item-limits.jsdom.test.tsx @@ -1,3 +1,4 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, fireEvent, render } from '@testing-library/react'; import { DashboardLanes } from '..'; import type { DashboardLanesLayoutItem } from '../types'; @@ -8,9 +9,6 @@ class MockResizeObserver { disconnect() {} } -let originalResizeObserver: typeof ResizeObserver; -let originalGetBoundingClientRect: typeof HTMLElement.prototype.getBoundingClientRect; - function rect( left: number, top: number, width: number, height: number ) { return { left, @@ -48,38 +46,39 @@ function setGeometry( containerWidth: number ) { async function activateAndStepRight( activator: Element ) { fireEvent.keyDown( activator, { code: 'Space' } ); act( () => { - jest.runOnlyPendingTimers(); + vi.runOnlyPendingTimers(); } ); fireEvent.keyDown( activator, { code: 'ArrowRight' } ); fireEvent.keyDown( activator, { code: 'Space' } ); await act( async () => { - jest.runOnlyPendingTimers(); + vi.runOnlyPendingTimers(); } ); } beforeEach( () => { - jest.useFakeTimers(); - originalResizeObserver = global.ResizeObserver; - ( global as unknown as { ResizeObserver: unknown } ).ResizeObserver = - MockResizeObserver; - originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect; - HTMLElement.prototype.getBoundingClientRect = function () { + vi.useFakeTimers(); + vi.stubGlobal( 'ResizeObserver', MockResizeObserver ); + vi.spyOn( + HTMLElement.prototype, + 'getBoundingClientRect' + ).mockImplementation( function ( this: HTMLElement ) { // eslint-disable-next-line testing-library/no-node-access const key = this.closest( '[data-wp-grid-item-key]' )?.getAttribute( 'data-wp-grid-item-key' ); return ( key && itemRects[ key ] ) || containerRect; - }; + } ); } ); afterEach( () => { - ( global as unknown as { ResizeObserver: unknown } ).ResizeObserver = - originalResizeObserver; - HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect; - jest.useRealTimers(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + vi.useRealTimers(); } ); -function renderLanes( onChangeLayout: jest.Mock ) { +function renderLanes( + onChangeLayout: ( layout: DashboardLanesLayoutItem[] ) => void +) { const layout: DashboardLanesLayoutItem[] = [ { key: 'a', width: 1 } ]; return render( { it( 'renders a stored span below the floor lifted to it', () => { setGeometry( 240 ); - const { container } = renderLanes( jest.fn() ); - const itemA = container.querySelector( '[data-wp-grid-item-key="a"]' ); - expect( itemA ).toHaveStyle( { gridColumn: 'span 2' } ); + const { container } = renderLanes( vi.fn() ); + const itemA = container.querySelector< HTMLElement >( + '[data-wp-grid-item-key="a"]' + ); + expect( itemA?.style.gridColumn ).toBe( 'span 2' ); } ); it( 'resizes from the rendered span, not the stored one', async () => { setGeometry( 240 ); - const onChangeLayout = jest.fn(); + const onChangeLayout = + vi.fn< ( layout: DashboardLanesLayoutItem[] ) => void >(); const { container } = renderLanes( onChangeLayout ); // One lane to the right of the rendered two-lane span. @@ -129,7 +131,8 @@ describe( 'DashboardLanes item limits', () => { it( 'commits nothing while the gesture stays inside the rendered span', async () => { setGeometry( 360 ); - const onChangeLayout = jest.fn(); + const onChangeLayout = + vi.fn< ( layout: DashboardLanesLayoutItem[] ) => void >(); const { container } = renderLanes( onChangeLayout ); await activateAndStepRight( getResizeHandle( container, 'a' ) ); diff --git a/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx b/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx index d4555568265f69..252a13cc2443d4 100644 --- a/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx +++ b/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx @@ -1,4 +1,5 @@ /* eslint-disable testing-library/no-container, testing-library/no-node-access -- Measurement behavior requires access to the hidden intrinsic tree and element geometry. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { createRef } from '@wordpress/element'; @@ -25,9 +26,6 @@ describe( 'Breadcrumb', () => { let originalClientWidth: PropertyDescriptor | undefined; let originalScrollWidth: PropertyDescriptor | undefined; let originalGetBoundingClientRect: typeof HTMLElement.prototype.getBoundingClientRect; - let originalResizeObserver: typeof ResizeObserver; - let originalRequestAnimationFrame: typeof requestAnimationFrame; - let originalCancelAnimationFrame: typeof cancelAnimationFrame; let originalFonts: PropertyDescriptor | undefined; beforeEach( () => { @@ -46,43 +44,46 @@ describe( 'Breadcrumb', () => { ); originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect; - originalResizeObserver = global.ResizeObserver; - originalRequestAnimationFrame = global.requestAnimationFrame; - originalCancelAnimationFrame = global.cancelAnimationFrame; originalFonts = Object.getOwnPropertyDescriptor( document, 'fonts' ); - global.ResizeObserver = class { - elements = new Set< Element >(); - private record: ResizeObserverRecord; - - constructor( callback: ResizeObserverCallback ) { - this.record = { - callback, - disconnected: false, - elements: this.elements, - }; - resizeObservers.push( this.record ); - } + vi.stubGlobal( + 'ResizeObserver', + class { + elements = new Set< Element >(); + private record: ResizeObserverRecord; + + constructor( callback: ResizeObserverCallback ) { + this.record = { + callback, + disconnected: false, + elements: this.elements, + }; + resizeObservers.push( this.record ); + } - observe( element: Element ) { - this.elements.add( element ); - } + observe( element: Element ) { + this.elements.add( element ); + } - unobserve( element: Element ) { - this.elements.delete( element ); - } + unobserve( element: Element ) { + this.elements.delete( element ); + } - disconnect() { - this.record.disconnected = true; - this.elements.clear(); + disconnect() { + this.record.disconnected = true; + this.elements.clear(); + } } - } as unknown as typeof ResizeObserver; + ); - global.requestAnimationFrame = jest.fn( ( callback ) => { - animationFrames.push( callback ); - return animationFrames.length; - } ); - global.cancelAnimationFrame = jest.fn(); + vi.stubGlobal( + 'requestAnimationFrame', + vi.fn( ( callback: FrameRequestCallback ) => { + animationFrames.push( callback ); + return animationFrames.length; + } ) + ); + vi.stubGlobal( 'cancelAnimationFrame', vi.fn() ); Object.defineProperty( HTMLElement.prototype, 'scrollWidth', { configurable: true, @@ -201,6 +202,8 @@ describe( 'Breadcrumb', () => { 'clientWidth', originalClientWidth ); + } else { + Reflect.deleteProperty( HTMLElement.prototype, 'clientWidth' ); } if ( originalScrollWidth ) { Object.defineProperty( @@ -208,12 +211,12 @@ describe( 'Breadcrumb', () => { 'scrollWidth', originalScrollWidth ); + } else { + Reflect.deleteProperty( HTMLElement.prototype, 'scrollWidth' ); } HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect; - global.ResizeObserver = originalResizeObserver; - global.requestAnimationFrame = originalRequestAnimationFrame; - global.cancelAnimationFrame = originalCancelAnimationFrame; + vi.unstubAllGlobals(); if ( originalFonts ) { Object.defineProperty( document, 'fonts', originalFonts ); } else { @@ -349,7 +352,7 @@ describe( 'Breadcrumb', () => { it( 'passes complete link props through a custom renderer', () => { const href = '/settings/general?section=writing#defaults'; - const renderLink = jest.fn( + const renderLink = vi.fn( ( { children: linkChildren, ...linkProps @@ -454,14 +457,12 @@ describe( 'Breadcrumb', () => { ); - const measurement = container.querySelector( + const measurement = container.querySelector< HTMLElement >( '.style-measurement-label' ); expect( measurement ).toHaveClass( 'item-class', 'render-class' ); - expect( measurement ).toHaveStyle( { - fontSize: '20px', - letterSpacing: '3px', - } ); + expect( measurement?.style.fontSize ).toBe( '20px' ); + expect( measurement?.style.letterSpacing ).toBe( '3px' ); } ); it( 'collapses items based on custom-rendered link widths', () => { @@ -736,7 +737,7 @@ describe( 'Breadcrumb', () => { it( 'activates an overflow link from the keyboard', async () => { const user = userEvent.setup(); - const handleClick = jest.fn( ( event ) => event.preventDefault() ); + const handleClick = vi.fn( ( event ) => event.preventDefault() ); availableWidth = 164; labelWidths.set( 'Section', 80 ); render( @@ -776,7 +777,7 @@ describe( 'Breadcrumb', () => { const user = userEvent.setup(); availableWidth = 84; labelWidths.set( 'Settings', 100 ); - const renderLink = jest.fn( + const renderLink = vi.fn( ( { children: linkChildren, ...linkProps @@ -1417,7 +1418,7 @@ describe( 'Breadcrumb', () => { const itemObserver = resizeObservers.find( ( observer ) => observer.elements.has( item! ) ); - const requestFrame = global.requestAnimationFrame as jest.Mock; + const requestFrame = vi.mocked( requestAnimationFrame ); requestFrame.mockClear(); act( () => { @@ -1441,8 +1442,7 @@ describe( 'Breadcrumb', () => { } ); it( 'falls back to the complete semantic trail without ResizeObserver', () => { - global.ResizeObserver = - undefined as unknown as typeof ResizeObserver; + vi.stubGlobal( 'ResizeObserver', undefined ); availableWidth = 40; renderDefaultTrail(); diff --git a/test/unit/jest.config.js b/test/unit/jest.config.js index e4f142c339b041..098becb5a3d3da 100644 --- a/test/unit/jest.config.js +++ b/test/unit/jest.config.js @@ -114,6 +114,7 @@ const commonProjectConfig = { module.exports = { rootDir: ROOT_DIR, + passWithNoTests: testMigration.jest.files.length === 0, projects: [ { ...commonProjectConfig, @@ -122,9 +123,12 @@ module.exports = { testEnvironmentOptions: { url: 'http://localhost/', }, - testMatch: testMigration.jest.files.map( - ( testPath ) => `/${ testPath }` - ), + // An empty testMatch array makes Jest discover every file. + testMatch: testMigration.jest.files.length + ? testMigration.jest.files.map( + ( testPath ) => `/${ testPath }` + ) + : [ '!**/*' ], }, ], watchPlugins: [ diff --git a/test/unit/test-migration.json b/test/unit/test-migration.json index f327da3e41ef59..ffc0fc1e574f43 100644 --- a/test/unit/test-migration.json +++ b/test/unit/test-migration.json @@ -1,12 +1,5 @@ { "jest": { - "files": [ - "packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts", - "packages/editor/src/store/utils/attach-media-in-post/test/index.jsdom.test.js", - "packages/editor/src/store/utils/attach-media-in-post/test/invalidate-attachment-resolutions.jsdom.test.js", - "packages/grid/src/dashboard-grid/test/item-limits.jsdom.test.tsx", - "packages/grid/src/dashboard-lanes/test/item-limits.jsdom.test.tsx", - "packages/ui/src/breadcrumb/test/index.jsdom.test.tsx" - ] + "files": [] } } diff --git a/test/unit/vitest-policy-exceptions.json b/test/unit/vitest-policy-exceptions.json index 5da21636e5d360..77ed0fd03650f9 100644 --- a/test/unit/vitest-policy-exceptions.json +++ b/test/unit/vitest-policy-exceptions.json @@ -18,6 +18,7 @@ "packages/grid/src/dashboard-lanes/test/keyboard-activation.jsdom.test.tsx": "Stubs ResizeObserver only to mount the lanes; assertions cover the deterministic keyboard activator DOM hierarchy.", "packages/grid/src/dashboard-lanes/test/use-lane-placement.jsdom.test.tsx": "Injects ResizeObserver entries and requestAnimationFrame scheduling to test deterministic lane-placement state without browser layout.", "packages/ui/src/form/primitives/control-with-error/test/control-with-error.jsdom.test.tsx": "Uses requestAnimationFrame only to schedule reportValidity after React state; assertions cover aria-describedby semantics.", - "packages/editor/src/components/collab-sidebar/test/board-store.jsdom.test.js": "Uses supplied DOMRect fixtures to test deterministic range-to-anchor calculations without relying on rendered layout." + "packages/editor/src/components/collab-sidebar/test/board-store.jsdom.test.js": "Uses supplied DOMRect fixtures to test deterministic range-to-anchor calculations without relying on rendered layout.", + "packages/ui/src/breadcrumb/test/index.jsdom.test.tsx": "Injects sizes, ResizeObserver notifications, font readiness, and animation frames to verify deterministic overflow state and measurement lifecycle. Real responsive layout is covered in index.browser.test.tsx." } } From 68ae1fd4c3da6146f18a5e7df5f4b2bd44afc4e1 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Thu, 10 Sep 2026 19:05:48 +0200 Subject: [PATCH 2/5] Test: Verify Breadcrumb interactions in Browser Mode --- .../test/cursor-dom-utils.jsdom.test.ts | 1 + .../src/breadcrumb/test/index.jsdom.test.tsx | 250 --------------- .../test/interactions.browser.test.tsx | 298 ++++++++++++++++++ 3 files changed, 299 insertions(+), 250 deletions(-) create mode 100644 packages/ui/src/breadcrumb/test/interactions.browser.test.tsx diff --git a/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts b/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts index 145c687a1414f4..7cb6afb266e546 100644 --- a/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts +++ b/packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts @@ -81,6 +81,7 @@ describe( 'cursor-dom-utils', () => { ); expect( result ).toBeNull(); + expect( document.createRange ).not.toHaveBeenCalled(); } ); } ); diff --git a/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx b/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx index 252a13cc2443d4..1a2f2932f29407 100644 --- a/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx +++ b/packages/ui/src/breadcrumb/test/index.jsdom.test.tsx @@ -630,149 +630,6 @@ describe( 'Breadcrumb', () => { ); } ); - it( 'contains exactly the collapsed link and closes on activation', async () => { - const user = userEvent.setup(); - availableWidth = 164; - labelWidths.set( 'Section', 80 ); - render( - - Home - event.preventDefault() } - > - Section - - Page - Current - - ); - - expect( screen.getAllByRole( 'link' ) ).toHaveLength( 2 ); - const trigger = screen.getByRole( 'button', { - name: 'Show 1 hidden breadcrumb item', - } ); - expect( trigger ).toHaveAttribute( 'aria-haspopup', 'menu' ); - expect( trigger ).toHaveAttribute( 'aria-expanded', 'false' ); - - await user.click( trigger ); - act( flushAllAnimationFrames ); - - const menu = await screen.findByRole( 'menu' ); - const menuLink = screen.getByRole( 'menuitem', { - name: 'Section', - } ); - expect( menu ).toContainElement( menuLink ); - expect( menuLink ).toHaveAttribute( 'href', '/section' ); - expect( - screen.queryByRole( 'menuitem', { name: 'Home' } ) - ).not.toBeInTheDocument(); - expect( - screen.queryByRole( 'menuitem', { name: 'Current' } ) - ).not.toBeInTheDocument(); - - await user.click( menuLink ); - act( flushAllAnimationFrames ); - await waitFor( () => - expect( screen.queryByRole( 'menu' ) ).not.toBeInTheDocument() - ); - } ); - - it( 'uses pluralized labels and supports menu keyboard behavior', async () => { - const user = userEvent.setup(); - availableWidth = 164; - labelWidths.set( 'Alpha', 70 ); - labelWidths.set( 'Beta', 60 ); - render( - - Home - - Alpha - - Beta - Page - Current - - ); - - const trigger = screen.getByRole( 'button', { - name: 'Show 2 hidden breadcrumb items', - } ); - act( () => trigger.focus() ); - await user.keyboard( ' ' ); - act( flushAllAnimationFrames ); - - const alpha = await screen.findByRole( 'menuitem', { - name: 'Alpha', - } ); - const beta = screen.getByRole( 'menuitem', { name: 'Beta' } ); - await waitFor( () => expect( alpha ).toHaveFocus() ); - - await user.keyboard( '{ArrowDown}' ); - expect( beta ).toHaveFocus(); - await user.keyboard( '{ArrowUp}' ); - expect( alpha ).toHaveFocus(); - await user.keyboard( '{End}' ); - expect( beta ).toHaveFocus(); - await user.keyboard( '{Home}' ); - expect( alpha ).toHaveFocus(); - await user.keyboard( 'b' ); - expect( beta ).toHaveFocus(); - await user.keyboard( '{Escape}' ); - act( flushAllAnimationFrames ); - await waitFor( () => expect( trigger ).toHaveFocus() ); - - await user.keyboard( '{Enter}' ); - act( flushAllAnimationFrames ); - const reopenedAlpha = await screen.findByRole( 'menuitem', { - name: 'Alpha', - } ); - await waitFor( () => expect( reopenedAlpha ).toHaveFocus() ); - await user.keyboard( '{Tab}' ); - act( flushAllAnimationFrames ); - await waitFor( () => - expect( screen.queryByRole( 'menu' ) ).not.toBeInTheDocument() - ); - } ); - - it( 'activates an overflow link from the keyboard', async () => { - const user = userEvent.setup(); - const handleClick = vi.fn( ( event ) => event.preventDefault() ); - availableWidth = 164; - labelWidths.set( 'Section', 80 ); - render( - - Home - - Section - - Page - Current - - ); - - const trigger = screen.getByRole( 'button', { - name: 'Show 1 hidden breadcrumb item', - } ); - act( () => trigger.focus() ); - await user.keyboard( '{Enter}' ); - act( flushAllAnimationFrames ); - const menuLink = await screen.findByRole( 'menuitem', { - name: 'Section', - } ); - await waitFor( () => expect( menuLink ).toHaveFocus() ); - - await user.keyboard( '{Enter}' ); - act( flushAllAnimationFrames ); - expect( handleClick ).toHaveBeenCalledTimes( 1 ); - await waitFor( () => - expect( screen.queryByRole( 'menu' ) ).not.toBeInTheDocument() - ); - } ); - it( 'passes the same custom renderer and complete href to menu links', async () => { const user = userEvent.setup(); availableWidth = 84; @@ -1072,113 +929,6 @@ describe( 'Breadcrumb', () => { } ); } ); - describe( 'truncated-label tooltips', () => { - it( 'keeps an untruncated current item out of the tab order', () => { - renderDefaultTrail(); - const current = screen.getByText( 'Current', { - selector: '[aria-current="page"]', - } ); - - expect( current ).not.toHaveAttribute( 'tabindex' ); - expect( screen.getAllByText( 'Current' ) ).toHaveLength( 2 ); - } ); - - it( 'makes a truncated current item focusable and preserves focus when it expands', async () => { - availableWidth = 70; - labelWidths.set( 'A very long current page', 100 ); - render( - - Home - - A very long current page - - - ); - - const current = screen.getByText( 'A very long current page', { - selector: '[aria-current="page"]', - } ); - await waitFor( () => - expect( current ).toHaveAttribute( 'tabindex', '0' ) - ); - act( () => current.focus() ); - await waitFor( () => - expect( - screen.getAllByText( 'A very long current page' ) - ).toHaveLength( 3 ) - ); - - availableWidth = 500; - notifyResize(); - await waitFor( () => expect( current ).toHaveFocus() ); - expect( current ).toHaveAttribute( 'tabindex', '0' ); - expect( current ).toHaveClass( 'style-outset-ring-focus-visible' ); - - act( () => current.blur() ); - await waitFor( () => - expect( current ).not.toHaveAttribute( 'tabindex' ) - ); - expect( current ).not.toHaveClass( - 'style-outset-ring-focus-visible' - ); - } ); - - it( 'shows the full text for an actually clipped link on focus', async () => { - labelWidths.set( 'Constrained ancestor', 100 ); - render( - - - Constrained ancestor - - Current - - ); - - const link = screen.getByRole( 'link', { - name: 'Constrained ancestor', - } ); - act( () => link.focus() ); - await waitFor( () => - expect( - screen.getAllByText( 'Constrained ancestor' ) - ).toHaveLength( 3 ) - ); - expect( link ).toHaveTextContent( 'Constrained ancestor' ); - } ); - - it( 'shows a clipped label tooltip on hover and dismisses it with Escape', async () => { - const user = userEvent.setup(); - labelWidths.set( 'Constrained ancestor', 100 ); - render( - - - Constrained ancestor - - Current - - ); - - const link = screen.getByRole( 'link', { - name: 'Constrained ancestor', - } ); - await user.hover( link ); - await waitFor( () => - expect( - screen.getAllByText( 'Constrained ancestor' ) - ).toHaveLength( 3 ) - ); - expect( link ).toHaveAccessibleName( 'Constrained ancestor' ); - - await user.keyboard( '{Escape}' ); - act( flushAllAnimationFrames ); - await waitFor( () => - expect( - screen.getAllByText( 'Constrained ancestor' ) - ).toHaveLength( 2 ) - ); - } ); - } ); - describe( 'measurement lifecycle', () => { it( 'subtracts focus-ring padding from the available inline size', () => { availableWidth = 164; diff --git a/packages/ui/src/breadcrumb/test/interactions.browser.test.tsx b/packages/ui/src/breadcrumb/test/interactions.browser.test.tsx new file mode 100644 index 00000000000000..7d4725b5acfacb --- /dev/null +++ b/packages/ui/src/breadcrumb/test/interactions.browser.test.tsx @@ -0,0 +1,298 @@ +import { describe, expect, it, vi } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; +import { screen, waitFor } from '@testing-library/react'; +import { render } from 'vitest-browser-react'; +import type { MouseEventHandler } from 'react'; +import * as Breadcrumb from '../index'; +import focusStyles from '../../utils/css/focus.module.scss'; + +function OverflowTrail( { + onClick, +}: { + onClick: MouseEventHandler< HTMLAnchorElement >; +} ) { + const itemStyle = { width: 80 }; + return ( + + + Home + + + Section + + + Page + + + Current + + + ); +} + +function CurrentTrail( { width }: { width: number } ) { + return ( + <> + + Home + + A very long current page + + + + + ); +} + +function ClippedLinkTrail() { + return ( + + + Constrained ancestor + + Current + + ); +} + +describe( 'Breadcrumb browser interactions', () => { + it( 'contains exactly the collapsed link and closes on activation', async () => { + await render( + event.preventDefault() } /> + ); + const trigger = page.getByRole( 'button', { + name: 'Show 1 hidden breadcrumb item', + } ); + await expect.element( trigger ).toBeVisible(); + expect( screen.getAllByRole( 'link' ) ).toHaveLength( 2 ); + await expect + .element( trigger ) + .toHaveAttribute( 'aria-haspopup', 'menu' ); + await expect + .element( trigger ) + .toHaveAttribute( 'aria-expanded', 'false' ); + await trigger.click(); + const menuLink = page.getByRole( 'menuitem', { name: 'Section' } ); + await expect.element( menuLink ).toBeVisible(); + await expect + .element( page.getByRole( 'menu' ) ) + .toContainElement( menuLink.element() ); + await expect.element( menuLink ).toHaveAttribute( 'href', '/section' ); + await expect + .element( page.getByRole( 'menuitem', { name: 'Home' } ) ) + .not.toBeInTheDocument(); + await expect + .element( page.getByRole( 'menuitem', { name: 'Current' } ) ) + .not.toBeInTheDocument(); + await menuLink.click(); + await expect + .element( page.getByRole( 'menu' ) ) + .not.toBeInTheDocument(); + } ); + + it( 'activates an overflow link from the keyboard', async () => { + const handleClick = vi.fn< MouseEventHandler< HTMLAnchorElement > >( + ( event ) => event.preventDefault() + ); + await render( ); + const trigger = page.getByRole( 'button', { + name: 'Show 1 hidden breadcrumb item', + } ); + await expect.element( trigger ).toBeVisible(); + await userEvent.tab(); + await expect + .element( page.getByRole( 'link', { name: 'Home' } ) ) + .toHaveFocus(); + await userEvent.tab(); + await expect.element( trigger ).toHaveFocus(); + await userEvent.keyboard( '{Enter}' ); + await expect + .element( page.getByRole( 'menuitem', { name: 'Section' } ) ) + .toHaveFocus(); + await userEvent.keyboard( '{Enter}' ); + expect( handleClick ).toHaveBeenCalledTimes( 1 ); + await expect + .element( page.getByRole( 'menu' ) ) + .not.toBeInTheDocument(); + } ); + + it( 'keeps an untruncated current item out of the tab order', async () => { + await render( ); + const current = screen.getByText( 'A very long current page', { + selector: '[aria-current="page"]', + } ); + expect( current.scrollWidth ).toBe( current.clientWidth ); + expect( current ).not.toHaveAttribute( 'tabindex' ); + expect( + screen.getAllByText( 'A very long current page' ) + ).toHaveLength( 2 ); + await userEvent.tab(); + await expect + .element( page.getByRole( 'link', { name: 'Home' } ) ) + .toHaveFocus(); + await userEvent.tab(); + await expect + .element( page.getByRole( 'button', { name: 'After breadcrumb' } ) ) + .toHaveFocus(); + } ); + + it( 'uses pluralized labels and supports menu keyboard behavior', async () => { + const itemStyle = { width: 80 }; + await render( + + + Home + + + Alpha + + + Beta + + + Page + + + Current + + + ); + + const trigger = page.getByRole( 'button', { + name: 'Show 2 hidden breadcrumb items', + } ); + await expect.element( trigger ).toBeVisible(); + await userEvent.tab(); + await expect + .element( page.getByRole( 'link', { name: 'Home' } ) ) + .toHaveFocus(); + await userEvent.tab(); + await expect.element( trigger ).toHaveFocus(); + await userEvent.keyboard( ' ' ); + + const alpha = page.getByRole( 'menuitem', { name: 'Alpha' } ); + const beta = page.getByRole( 'menuitem', { name: 'Beta' } ); + await expect.element( alpha ).toHaveFocus(); + await userEvent.keyboard( '{ArrowDown}' ); + await expect.element( beta ).toHaveFocus(); + await userEvent.keyboard( '{ArrowUp}' ); + await expect.element( alpha ).toHaveFocus(); + await userEvent.keyboard( '{End}' ); + await expect.element( beta ).toHaveFocus(); + await userEvent.keyboard( '{Home}' ); + await expect.element( alpha ).toHaveFocus(); + await userEvent.keyboard( 'b' ); + await expect.element( beta ).toHaveFocus(); + await userEvent.keyboard( '{Escape}' ); + await expect.element( trigger ).toHaveFocus(); + + await userEvent.keyboard( '{Enter}' ); + await expect.element( alpha ).toHaveFocus(); + await userEvent.tab(); + await expect + .element( page.getByRole( 'menu' ) ) + .not.toBeInTheDocument(); + } ); + + it( 'makes a truncated current item focusable and preserves focus when it expands', async () => { + const view = await render( ); + const current = screen.getByText( 'A very long current page', { + selector: '[aria-current="page"]', + } ); + await waitFor( () => { + expect( current.scrollWidth ).toBeGreaterThan( + current.clientWidth + ); + expect( current ).toHaveAttribute( 'tabindex', '0' ); + } ); + await userEvent.tab(); + await expect + .element( + page.getByRole( 'button', { name: /hidden breadcrumb/ } ) + ) + .toHaveFocus(); + await userEvent.tab(); + await expect.element( current ).toHaveFocus(); + await waitFor( () => + expect( + screen.getAllByText( 'A very long current page' ) + ).toHaveLength( 3 ) + ); + expect( + screen.getByText( 'A very long current page', { + selector: '[data-open]', + } ) + ).toBeVisible(); + + await view.rerender( ); + await waitFor( () => { + expect( current.scrollWidth ).toBe( current.clientWidth ); + expect( current ).toHaveFocus(); + } ); + expect( current ).toHaveAttribute( 'tabindex', '0' ); + expect( current ).toHaveClass( + focusStyles[ 'outset-ring--focus-visible' ] + ); + + await userEvent.tab(); + await expect + .element( page.getByRole( 'button', { name: 'After breadcrumb' } ) ) + .toHaveFocus(); + await expect.element( current ).not.toHaveAttribute( 'tabindex' ); + expect( current ).not.toHaveClass( + focusStyles[ 'outset-ring--focus-visible' ] + ); + } ); + + it( 'shows the full text for an actually clipped link on focus', async () => { + await render( ); + const link = screen.getByRole( 'link', { + name: 'Constrained ancestor', + } ); + expect( link.scrollWidth ).toBeGreaterThan( link.clientWidth ); + await userEvent.tab(); + await expect.element( link ).toHaveFocus(); + await waitFor( () => + expect( + screen.getAllByText( 'Constrained ancestor' ) + ).toHaveLength( 3 ) + ); + expect( + screen.getByText( 'Constrained ancestor', { + selector: '[data-open]', + } ) + ).toBeVisible(); + expect( link ).toHaveTextContent( 'Constrained ancestor' ); + } ); + + it( 'shows a clipped label tooltip on hover and dismisses it with Escape', async () => { + await render( ); + const link = page.getByRole( 'link', { name: 'Constrained ancestor' } ); + const element = link.element(); + expect( element.scrollWidth ).toBeGreaterThan( element.clientWidth ); + await link.hover(); + await waitFor( () => + expect( + screen.getAllByText( 'Constrained ancestor' ) + ).toHaveLength( 3 ) + ); + expect( + screen.getByText( 'Constrained ancestor', { + selector: '[data-open]', + } ) + ).toBeVisible(); + await expect + .element( link ) + .toHaveAccessibleName( 'Constrained ancestor' ); + await userEvent.keyboard( '{Escape}' ); + await waitFor( () => + expect( + screen.getAllByText( 'Constrained ancestor' ) + ).toHaveLength( 2 ) + ); + } ); +} ); From 748020290e07480eecab5d95d44a52bd3b0e8bec Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Thu, 10 Sep 2026 19:39:49 +0200 Subject: [PATCH 3/5] Test: Use native browser coverage and reduce Vitest exceptions --- .../color-picker/test/index.browser.test.tsx | 69 +-- .../test/index.browser.test.tsx | 59 +- .../test/index.browser.test.tsx | 9 +- ...est.tsx => range-control.browser.test.tsx} | 13 +- .../test/infinite-scroll.browser.test.tsx | 3 +- .../test/item-interactions.browser.test.tsx | 50 ++ .../test/item-interactions.jsdom.test.tsx | 64 --- ...x => keyboard-activation.browser.test.tsx} | 44 +- .../test/item-interactions.browser.test.tsx | 50 ++ .../test/item-interactions.jsdom.test.tsx | 64 --- ...x => keyboard-activation.browser.test.tsx} | 44 +- .../test/rectangle-stencil.browser.test.tsx | 11 +- .../components/test/cropper.browser.test.tsx | 19 +- .../test/control-with-error.browser.test.tsx | 499 ++++++++++++++++ .../test/control-with-error.jsdom.test.tsx | 536 +----------------- .../test/fixtures/validated-input-control.tsx | 40 ++ ...y-scroll-state-attributes.browser.test.tsx | 9 +- test/unit/VITEST_MIGRATION.md | 5 + test/unit/vitest-policy-exceptions.json | 14 +- 19 files changed, 759 insertions(+), 843 deletions(-) rename packages/components/src/validated-form-controls/test/{range-control.jsdom.test.tsx => range-control.browser.test.tsx} (87%) create mode 100644 packages/grid/src/dashboard-grid/test/item-interactions.browser.test.tsx delete mode 100644 packages/grid/src/dashboard-grid/test/item-interactions.jsdom.test.tsx rename packages/grid/src/dashboard-grid/test/{keyboard-activation.jsdom.test.tsx => keyboard-activation.browser.test.tsx} (55%) create mode 100644 packages/grid/src/dashboard-lanes/test/item-interactions.browser.test.tsx delete mode 100644 packages/grid/src/dashboard-lanes/test/item-interactions.jsdom.test.tsx rename packages/grid/src/dashboard-lanes/test/{keyboard-activation.jsdom.test.tsx => keyboard-activation.browser.test.tsx} (54%) create mode 100644 packages/ui/src/form/primitives/control-with-error/test/control-with-error.browser.test.tsx create mode 100644 packages/ui/src/form/primitives/control-with-error/test/fixtures/validated-input-control.tsx diff --git a/packages/components/src/color-picker/test/index.browser.test.tsx b/packages/components/src/color-picker/test/index.browser.test.tsx index d82e3392c84719..adc17ca4242132 100644 --- a/packages/components/src/color-picker/test/index.browser.test.tsx +++ b/packages/components/src/color-picker/test/index.browser.test.tsx @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import { userEvent } from 'vitest/browser'; -import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { screen, waitFor } from '@testing-library/react'; import { render } from 'vitest-browser-react'; import { useState } from '@wordpress/element'; import { ColorPicker } from '..'; @@ -603,14 +603,23 @@ describe( 'ColorPicker', () => { const bounds = element.getBoundingClientRect(); expect( bounds.width ).toBeGreaterThan( 0 ); expect( bounds.height ).toBeGreaterThan( 0 ); - const clientX = bounds.left + bounds.width * x; - const clientY = bounds.top + bounds.height * y; - return { - clientX, - clientY, - pageX: clientX + window.scrollX, - pageY: clientY + window.scrollY, - }; + return { x: bounds.width * x, y: bounds.height * y }; + }; + + const dragToBlack = async ( element: HTMLElement ) => { + // Black is at the bottom boundary, just outside the slider's hit area. + // Release over the picker below it so native mouse movement reaches v = 0. + // eslint-disable-next-line testing-library/no-node-access -- The picker background has no accessible role. + const picker = element.closest< HTMLElement >( '.react-colorful' )!; + const bounds = element.getBoundingClientRect(); + const pickerBounds = picker.getBoundingClientRect(); + await userEvent.dragAndDrop( element, picker, { + sourcePosition: pointAt( element, 0.8, 0.5 ), + targetPosition: { + x: bounds.left - pickerBounds.left + bounds.width * 0.8, + y: bounds.bottom - pickerBounds.top + 1, + }, + } ); }; const getPointerPosition = ( pointer: HTMLElement ) => { @@ -686,11 +695,8 @@ describe( 'ColorPicker', () => { ) as HTMLElement; expect( parseFloat( pointer.style.left ) ).toBeGreaterThan( 50 ); - // Click the bottom of the saturation surface (v = 0) at ~80% saturation. - fireEvent.mouseDown( interactive, { - buttons: 1, - ...pointAt( interactive, 0.8, 1 ), - } ); + // Drag to the bottom of the saturation surface at 80% saturation. + await dragToBlack( interactive ); expectPointerPosition( pointer, { top: 100 } ); // Lossy HSVA→HSLA→HSVA sync would snap left to 0%. @@ -716,30 +722,7 @@ describe( 'ColorPicker', () => { '.react-colorful__saturation-pointer' ) as HTMLElement; - // Full pointer lifecycle so isPointerInteractingRef is exercised - // and prevHslaRef stays in sync across mid-gesture parent updates. - fireEvent.pointerDown( interactive, { - pointerId: 1, - buttons: 1, - ...pointAt( interactive, 0.8, 0.5 ), - } ); - fireEvent.mouseDown( interactive, { - buttons: 1, - ...pointAt( interactive, 0.8, 0.5 ), - } ); - fireEvent.mouseMove( interactive, { - buttons: 1, - ...pointAt( interactive, 0.8, 1 ), - } ); - fireEvent.pointerUp( interactive, { - pointerId: 1, - buttons: 0, - ...pointAt( interactive, 0.8, 1 ), - } ); - fireEvent.mouseUp( interactive, { - buttons: 0, - ...pointAt( interactive, 0.8, 1 ), - } ); + await dragToBlack( interactive ); expectPointerPosition( pointer, { top: 100 } ); expect( getPointerPosition( pointer ).left ).toBeGreaterThan( 50 ); @@ -904,9 +887,8 @@ describe( 'ColorPicker', () => { const colorSlider = screen.getByRole( 'slider', { name: 'Color' } ); onChange.mockClear(); - fireEvent.mouseDown( colorSlider, { - buttons: 1, - ...pointAt( colorSlider, 0.5, 0 ), + await userEvent.click( colorSlider, { + position: pointAt( colorSlider, 0.5, 0 ), } ); expect( onChange ).toHaveBeenLastCalledWith( '#80d4ff' ); @@ -933,9 +915,8 @@ describe( 'ColorPicker', () => { const colorSlider = screen.getByRole( 'slider', { name: 'Color' } ); onChange.mockClear(); - fireEvent.mouseDown( colorSlider, { - buttons: 1, - ...pointAt( colorSlider, 0.5, 0.5 ), + await userEvent.click( colorSlider, { + position: pointAt( colorSlider, 0.5, 0.5 ), } ); expect( onChange ).toHaveBeenLastCalledWith( '#416c81' ); diff --git a/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx b/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx index 1004c6702c0730..1fa3b55b07fe51 100644 --- a/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx +++ b/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx @@ -1,8 +1,11 @@ import { describe, expect, it, vi } from 'vitest'; import { userEvent } from 'vitest/browser'; -import { act, fireEvent, screen, waitFor } from '@testing-library/react'; +import { screen, waitFor } from '@testing-library/react'; import { render } from 'vitest-browser-react'; import { useState } from '@wordpress/element'; +// Load the picker, buttons and portaled popover as a consumer does. +// eslint-disable-next-line @wordpress/no-non-module-stylesheet-imports +import '../../style.scss'; import CustomGradientPicker from '../'; import CustomGradientBar from '../gradient-bar'; import { KEYBOARD_CONTROL_POINT_VARIATION } from '../gradient-bar/constants'; @@ -30,8 +33,8 @@ describe( 'CustomGradientPicker', () => { const barBounds = bar.getBoundingClientRect(); expect( barBounds.width ).toBeGreaterThan( 0 ); // Hover mid-bar so the insert-point control appears (away from 0%/100%). - fireEvent.mouseMove( bar, { - clientX: barBounds.left + barBounds.width / 2, + await userEvent.hover( bar, { + position: { x: barBounds.width / 2, y: barBounds.height / 2 }, } ); // eslint-disable-next-line testing-library/no-node-access @@ -39,7 +42,7 @@ describe( 'CustomGradientPicker', () => { '.components-custom-gradient-picker__insert-point-dropdown' ) as HTMLElement; expect( insertButton ).toBeTruthy(); - await act( async () => insertButton.click() ); + await userEvent.click( insertButton ); const colorSlider = screen.getByRole( 'slider', { name: 'Color' } ); const sliderBounds = colorSlider.getBoundingClientRect(); @@ -48,14 +51,11 @@ describe( 'CustomGradientPicker', () => { // Choose a saturated mid-brightness color — creates the new stop and // exercises parent gradient updates while picking. - const clientX = sliderBounds.left + sliderBounds.width * 0.8; - const clientY = sliderBounds.top + sliderBounds.height * 0.2; - fireEvent.mouseDown( colorSlider, { - buttons: 1, - clientX, - clientY, - pageX: clientX + window.scrollX, - pageY: clientY + window.scrollY, + await userEvent.click( colorSlider, { + position: { + x: sliderBounds.width * 0.8, + y: sliderBounds.height * 0.2, + }, } ); // ColorPicker content is portaled; pointer has no accessible role. @@ -85,7 +85,7 @@ describe( 'CustomGradientPicker', () => { // Close the portaled popover so later tests are not affected by // asynchronous Popover position updates. - await act( async () => insertButton.click() ); + await userEvent.click( insertButton ); await waitFor( () => { expect( screen.queryByRole( 'slider', { name: 'Color' } ) @@ -204,9 +204,6 @@ describe( 'CustomGradientBar', () => { ] ); } ); - // Dragging is driven by window-level listeners attached on mousedown, and - // the position comes from the markers container's box, so that has to be - // given one in jsdom. it( 'moves a control point when dragged', async () => { const onChange = vi.fn(); @@ -223,18 +220,22 @@ describe( 'CustomGradientBar', () => { const markers = container.querySelector( '.components-custom-gradient-picker__markers-container' ) as HTMLElement; - markers.getBoundingClientRect = () => - ( { x: 0, width: 200 } ) as DOMRect; + expect( markers.getBoundingClientRect().width ).toBeGreaterThan( 0 ); + // eslint-disable-next-line testing-library/no-node-access -- The gradient background has no accessible role. + const bar = markers.closest< HTMLElement >( + '.components-custom-gradient-picker__gradient-bar' + )!; + const bounds = bar.getBoundingClientRect(); const [ firstPoint ] = screen.getAllByRole( 'button', { name: /Gradient control point/, } ); - fireEvent.mouseDown( firstPoint ); - fireEvent.mouseMove( window, { clientX: 100 } ); - fireEvent.mouseUp( window ); + await userEvent.dragAndDrop( firstPoint, bar, { + targetPosition: { x: bounds.width / 2, y: bounds.height / 2 }, + } ); - // 100px into a 200px container is 50%. + // The midpoint of the rendered container is 50%. expect( onChange ).toHaveBeenCalledWith( [ { position: 50, color: 'rgb(0,0,0)' }, POINTS[ 1 ], @@ -258,16 +259,20 @@ describe( 'CustomGradientBar', () => { const markers = container.querySelector( '.components-custom-gradient-picker__markers-container' ) as HTMLElement; - markers.getBoundingClientRect = () => - ( { x: 0, width: 200 } ) as DOMRect; + expect( markers.getBoundingClientRect().width ).toBeGreaterThan( 0 ); + // eslint-disable-next-line testing-library/no-node-access -- The gradient background has no accessible role. + const bar = markers.closest< HTMLElement >( + '.components-custom-gradient-picker__gradient-bar' + )!; + const bounds = bar.getBoundingClientRect(); const [ firstPoint ] = screen.getAllByRole( 'button', { name: /Gradient control point/, } ); - fireEvent.mouseDown( firstPoint ); - fireEvent.mouseMove( window, { clientX: 100 } ); - fireEvent.mouseUp( window ); + await userEvent.dragAndDrop( firstPoint, bar, { + targetPosition: { x: bounds.width / 2, y: bounds.height / 2 }, + } ); expect( onChange ).not.toHaveBeenCalled(); } ); diff --git a/packages/components/src/focal-point-picker/test/index.browser.test.tsx b/packages/components/src/focal-point-picker/test/index.browser.test.tsx index 2fbe69f504a6a0..cfe22547e65fce 100644 --- a/packages/components/src/focal-point-picker/test/index.browser.test.tsx +++ b/packages/components/src/focal-point-picker/test/index.browser.test.tsx @@ -53,15 +53,16 @@ describe( 'FocalPointPicker', () => { const draggableArea = screen.getByRole( 'button' ); - // `user-event` is not capable of testing drag interactions properly. - // we could consider using playwright instead. + // Start a gesture without releasing it so Tab can interrupt it. fireEvent.mouseDown( draggableArea ); expect( mockOnDrag ).not.toHaveBeenCalled(); expect( mockOnDragEnd ).not.toHaveBeenCalled(); - fireEvent.blur( draggableArea ); - fireEvent.mouseMove( draggableArea ); + expect( draggableArea ).toHaveFocus(); + await userEvent.tab(); + expect( draggableArea ).not.toHaveFocus(); + await userEvent.hover( draggableArea ); expect( mockOnDrag ).not.toHaveBeenCalled(); expect( mockOnDragEnd ).toHaveBeenCalledTimes( 1 ); diff --git a/packages/components/src/validated-form-controls/test/range-control.jsdom.test.tsx b/packages/components/src/validated-form-controls/test/range-control.browser.test.tsx similarity index 87% rename from packages/components/src/validated-form-controls/test/range-control.jsdom.test.tsx rename to packages/components/src/validated-form-controls/test/range-control.browser.test.tsx index fb79e683ccedbc..7fd16ff1bf7665 100644 --- a/packages/components/src/validated-form-controls/test/range-control.jsdom.test.tsx +++ b/packages/components/src/validated-form-controls/test/range-control.browser.test.tsx @@ -1,14 +1,13 @@ import { describe, expect, it } from 'vitest'; -import { render, screen, waitFor } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; +import { screen, waitFor } from '@testing-library/react'; +import { render } from 'vitest-browser-react'; +import { userEvent } from 'vitest/browser'; import { useState, useRef } from '@wordpress/element'; import { ValidatedRangeControl } from '../components'; -globalThis.wpVitest.mockMatchMedia(); - describe( 'ValidatedRangeControl', () => { - it( 'should preserve the help description', () => { - render( + it( 'should preserve the help description', async () => { + await render( ); @@ -57,7 +56,7 @@ describe( 'ValidatedRangeControl', () => { ); } - render( ); + await render( ); const slider = screen.getByRole( 'slider', { name: 'Opacity' } ); expect( slider ).toHaveAccessibleDescription( 'Set the opacity.' ); diff --git a/packages/dataviews/src/dataviews/test/infinite-scroll.browser.test.tsx b/packages/dataviews/src/dataviews/test/infinite-scroll.browser.test.tsx index 47486fb3af9378..34ce31dad99f95 100644 --- a/packages/dataviews/src/dataviews/test/infinite-scroll.browser.test.tsx +++ b/packages/dataviews/src/dataviews/test/infinite-scroll.browser.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import { render } from 'vitest-browser-react'; import { describe, expect, it, vi } from 'vitest'; import DataViews from '../index'; @@ -66,7 +66,6 @@ describe( 'DataViews browser scrolling', () => { } ); layoutContainer!.scrollTop = layoutContainer!.scrollHeight; - fireEvent.scroll( layoutContainer! ); await waitFor( () => { expect( onChangeView ).toHaveBeenCalledWith( diff --git a/packages/grid/src/dashboard-grid/test/item-interactions.browser.test.tsx b/packages/grid/src/dashboard-grid/test/item-interactions.browser.test.tsx new file mode 100644 index 00000000000000..2e6f45e7663222 --- /dev/null +++ b/packages/grid/src/dashboard-grid/test/item-interactions.browser.test.tsx @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-react'; +import { DashboardGrid } from '..'; + +async function renderItem( flags: { + draggable?: boolean; + resizable?: boolean; +} ) { + const { container } = await render( + +
A
+
+ ); + return { + activator: container.querySelector( + '[aria-roledescription="sortable"]' + ), + resizeHandle: container.querySelector( + '[aria-roledescription="draggable"]' + ), + }; +} + +describe( 'DashboardGrid item interactions', () => { + it( 'drags and resizes by default in edit mode', async () => { + const { activator, resizeHandle } = await renderItem( {} ); + expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); + expect( resizeHandle ).not.toBeNull(); + } ); + + it( 'keeps an item in place when draggable is false', async () => { + const { activator, resizeHandle } = await renderItem( { + draggable: false, + } ); + expect( activator ).toHaveAttribute( 'aria-disabled', 'true' ); + expect( resizeHandle ).not.toBeNull(); + } ); + + it( 'keeps an item at its size when resizable is false', async () => { + const { activator, resizeHandle } = await renderItem( { + resizable: false, + } ); + expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); + expect( resizeHandle ).toBeNull(); + } ); +} ); diff --git a/packages/grid/src/dashboard-grid/test/item-interactions.jsdom.test.tsx b/packages/grid/src/dashboard-grid/test/item-interactions.jsdom.test.tsx deleted file mode 100644 index 0e709d53908091..00000000000000 --- a/packages/grid/src/dashboard-grid/test/item-interactions.jsdom.test.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { render } from '@testing-library/react'; -import { DashboardGrid } from '..'; - -class MockResizeObserver { - observe() {} - unobserve() {} - disconnect() {} -} - -let originalResizeObserver: typeof ResizeObserver; - -beforeEach( () => { - originalResizeObserver = globalThis.ResizeObserver; - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - MockResizeObserver; -} ); - -afterEach( () => { - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - originalResizeObserver; -} ); - -/* eslint-disable testing-library/no-container */ -function renderItem( flags: { draggable?: boolean; resizable?: boolean } ) { - const { container } = render( - -
A
-
- ); - return { - activator: container.querySelector( - '[aria-roledescription="sortable"]' - ), - resizeHandle: container.querySelector( - '[aria-roledescription="draggable"]' - ), - }; -} -/* eslint-enable testing-library/no-container */ - -describe( 'DashboardGrid item interactions', () => { - it( 'drags and resizes by default in edit mode', () => { - const { activator, resizeHandle } = renderItem( {} ); - expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); - expect( resizeHandle ).not.toBeNull(); - } ); - - it( 'keeps an item in place when draggable is false', () => { - const { activator, resizeHandle } = renderItem( { draggable: false } ); - expect( activator ).toHaveAttribute( 'aria-disabled', 'true' ); - expect( resizeHandle ).not.toBeNull(); - } ); - - it( 'keeps an item at its size when resizable is false', () => { - const { activator, resizeHandle } = renderItem( { resizable: false } ); - expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); - expect( resizeHandle ).toBeNull(); - } ); -} ); diff --git a/packages/grid/src/dashboard-grid/test/keyboard-activation.jsdom.test.tsx b/packages/grid/src/dashboard-grid/test/keyboard-activation.browser.test.tsx similarity index 55% rename from packages/grid/src/dashboard-grid/test/keyboard-activation.jsdom.test.tsx rename to packages/grid/src/dashboard-grid/test/keyboard-activation.browser.test.tsx index cf709d5040bc40..a4443d303d8a08 100644 --- a/packages/grid/src/dashboard-grid/test/keyboard-activation.jsdom.test.tsx +++ b/packages/grid/src/dashboard-grid/test/keyboard-activation.browser.test.tsx @@ -1,40 +1,14 @@ -import { render } from '@testing-library/react'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { userEvent } from 'vitest/browser'; +import { render } from 'vitest-browser-react'; +import { describe, expect, it } from 'vitest'; import { DashboardGrid } from '..'; -class MockResizeObserver { - observed: Set< Element > = new Set(); - observe( element: Element ) { - this.observed.add( element ); - } - unobserve( element: Element ) { - this.observed.delete( element ); - } - disconnect() { - this.observed.clear(); - } -} - -let originalResizeObserver: typeof ResizeObserver; - -beforeEach( () => { - originalResizeObserver = globalThis.ResizeObserver; - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - MockResizeObserver; -} ); - -afterEach( () => { - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - originalResizeObserver; -} ); - describe( 'DashboardGrid keyboard activation', () => { - it( 'places the dnd-kit keyboard activator on the inner wrapper, not the outer item', () => { + it( 'places the dnd-kit keyboard activator on the inner wrapper, not the outer item', async () => { // Verifies the DOM hierarchy: keyboard activation needs the // focused node and the keydown listener to share a node, so // the activator must live nested inside the outer item. - /* eslint-disable testing-library/no-container, testing-library/no-node-access */ - const { container } = render( + const { container } = await render( { const item = items[ 0 ]; expect( activator ).not.toBe( item ); expect( item.contains( activator! ) ).toBe( true ); - /* eslint-enable testing-library/no-container, testing-library/no-node-access */ + + await userEvent.tab(); + expect( activator ).toHaveFocus(); + await userEvent.keyboard( '[Space]' ); + expect( activator ).toHaveAttribute( 'aria-pressed', 'true' ); + await userEvent.keyboard( '[Escape]' ); + expect( activator ).not.toHaveAttribute( 'aria-pressed' ); } ); } ); diff --git a/packages/grid/src/dashboard-lanes/test/item-interactions.browser.test.tsx b/packages/grid/src/dashboard-lanes/test/item-interactions.browser.test.tsx new file mode 100644 index 00000000000000..6749b7f38eff8c --- /dev/null +++ b/packages/grid/src/dashboard-lanes/test/item-interactions.browser.test.tsx @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-react'; +import { DashboardLanes } from '..'; + +async function renderItem( flags: { + draggable?: boolean; + resizable?: boolean; +} ) { + const { container } = await render( + +
A
+
+ ); + return { + activator: container.querySelector( + '[aria-roledescription="sortable"]' + ), + resizeHandle: container.querySelector( + '[aria-roledescription="draggable"]' + ), + }; +} + +describe( 'DashboardLanes item interactions', () => { + it( 'drags and resizes by default in edit mode', async () => { + const { activator, resizeHandle } = await renderItem( {} ); + expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); + expect( resizeHandle ).not.toBeNull(); + } ); + + it( 'keeps an item in place when draggable is false', async () => { + const { activator, resizeHandle } = await renderItem( { + draggable: false, + } ); + expect( activator ).toHaveAttribute( 'aria-disabled', 'true' ); + expect( resizeHandle ).not.toBeNull(); + } ); + + it( 'keeps an item at its size when resizable is false', async () => { + const { activator, resizeHandle } = await renderItem( { + resizable: false, + } ); + expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); + expect( resizeHandle ).toBeNull(); + } ); +} ); diff --git a/packages/grid/src/dashboard-lanes/test/item-interactions.jsdom.test.tsx b/packages/grid/src/dashboard-lanes/test/item-interactions.jsdom.test.tsx deleted file mode 100644 index 1d91713b4e7933..00000000000000 --- a/packages/grid/src/dashboard-lanes/test/item-interactions.jsdom.test.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { render } from '@testing-library/react'; -import { DashboardLanes } from '..'; - -class MockResizeObserver { - observe() {} - unobserve() {} - disconnect() {} -} - -let originalResizeObserver: typeof ResizeObserver; - -beforeEach( () => { - originalResizeObserver = globalThis.ResizeObserver; - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - MockResizeObserver; -} ); - -afterEach( () => { - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - originalResizeObserver; -} ); - -/* eslint-disable testing-library/no-container */ -function renderItem( flags: { draggable?: boolean; resizable?: boolean } ) { - const { container } = render( - -
A
-
- ); - return { - activator: container.querySelector( - '[aria-roledescription="sortable"]' - ), - resizeHandle: container.querySelector( - '[aria-roledescription="draggable"]' - ), - }; -} -/* eslint-enable testing-library/no-container */ - -describe( 'DashboardLanes item interactions', () => { - it( 'drags and resizes by default in edit mode', () => { - const { activator, resizeHandle } = renderItem( {} ); - expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); - expect( resizeHandle ).not.toBeNull(); - } ); - - it( 'keeps an item in place when draggable is false', () => { - const { activator, resizeHandle } = renderItem( { draggable: false } ); - expect( activator ).toHaveAttribute( 'aria-disabled', 'true' ); - expect( resizeHandle ).not.toBeNull(); - } ); - - it( 'keeps an item at its size when resizable is false', () => { - const { activator, resizeHandle } = renderItem( { resizable: false } ); - expect( activator ).toHaveAttribute( 'aria-disabled', 'false' ); - expect( resizeHandle ).toBeNull(); - } ); -} ); diff --git a/packages/grid/src/dashboard-lanes/test/keyboard-activation.jsdom.test.tsx b/packages/grid/src/dashboard-lanes/test/keyboard-activation.browser.test.tsx similarity index 54% rename from packages/grid/src/dashboard-lanes/test/keyboard-activation.jsdom.test.tsx rename to packages/grid/src/dashboard-lanes/test/keyboard-activation.browser.test.tsx index 507c91e6405b69..5db78ab0308292 100644 --- a/packages/grid/src/dashboard-lanes/test/keyboard-activation.jsdom.test.tsx +++ b/packages/grid/src/dashboard-lanes/test/keyboard-activation.browser.test.tsx @@ -1,40 +1,14 @@ -import { render } from '@testing-library/react'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { userEvent } from 'vitest/browser'; +import { render } from 'vitest-browser-react'; +import { describe, expect, it } from 'vitest'; import { DashboardLanes } from '..'; -class MockResizeObserver { - observed: Set< Element > = new Set(); - observe( element: Element ) { - this.observed.add( element ); - } - unobserve( element: Element ) { - this.observed.delete( element ); - } - disconnect() { - this.observed.clear(); - } -} - -let originalResizeObserver: typeof ResizeObserver; - -beforeEach( () => { - originalResizeObserver = globalThis.ResizeObserver; - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - MockResizeObserver; -} ); - -afterEach( () => { - ( globalThis as unknown as { ResizeObserver: unknown } ).ResizeObserver = - originalResizeObserver; -} ); - describe( 'DashboardLanes keyboard activation', () => { - it( 'places the dnd-kit keyboard activator on the inner wrapper, not the outer item', () => { + it( 'places the dnd-kit keyboard activator on the inner wrapper, not the outer item', async () => { // Verifies the DOM hierarchy: keyboard activation needs the // focused node and the keydown listener to share a node, so // the activator must live nested inside the outer item. - /* eslint-disable testing-library/no-container, testing-library/no-node-access */ - const { container } = render( + const { container } = await render(
A
@@ -56,6 +30,12 @@ describe( 'DashboardLanes keyboard activation', () => { expect( lanesItem ).not.toBeNull(); expect( activator ).not.toBe( lanesItem ); expect( lanesItem!.contains( activator! ) ).toBe( true ); - /* eslint-enable testing-library/no-container, testing-library/no-node-access */ + + await userEvent.tab(); + expect( activator ).toHaveFocus(); + await userEvent.keyboard( '[Space]' ); + expect( activator ).toHaveAttribute( 'aria-pressed', 'true' ); + await userEvent.keyboard( '[Escape]' ); + expect( activator ).not.toHaveAttribute( 'aria-pressed' ); } ); } ); diff --git a/packages/media-editor/src/image-editor/react/components/stencils/test/rectangle-stencil.browser.test.tsx b/packages/media-editor/src/image-editor/react/components/stencils/test/rectangle-stencil.browser.test.tsx index 58eb5a5be9d80f..dc612cabdcdf89 100644 --- a/packages/media-editor/src/image-editor/react/components/stencils/test/rectangle-stencil.browser.test.tsx +++ b/packages/media-editor/src/image-editor/react/components/stencils/test/rectangle-stencil.browser.test.tsx @@ -353,17 +353,10 @@ describe( 'RectangleStencil', () => { vi.spyOn( firstHandle, 'focus' ); - fireEvent.pointerDown( firstHandle, { - button: 0, - clientX: 100, - clientY: 100, - pointerId: 1, - } ); - fireEvent.pointerUp( firstHandle, { - pointerId: 1, - } ); + await userEvent.dragAndDrop( firstHandle, firstHandle ); expect( firstHandle.focus ).toHaveBeenCalled(); + expect( firstHandle ).toHaveFocus(); } ); it( 'does not start a pointer resize while resizing is disabled', async () => { diff --git a/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx b/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx index 211e17974ea404..fdd1bc11e3576b 100644 --- a/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx +++ b/packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx @@ -756,7 +756,7 @@ describe( 'Cropper', () => { freeformCrop: true, onGestureStart, }; - const { rerender } = await render( ); + const { rerender } = await renderCropper( ); await screen.findByRole( 'button', { name: 'Resize from top-left corner', @@ -764,7 +764,7 @@ describe( 'Cropper', () => { const canvas = screen.getByRole( 'group', { name: 'Crop area' } ); // A wheel zoom opens a debounced gesture. - fireEvent.wheel( canvas, { deltaY: -120, clientX: 100, clientY: 100 } ); + await userEvent.wheel( canvas, { delta: { y: -120 } } ); await waitFor( () => expect( onGestureStart ).toHaveBeenCalled() ); // Saving cancels it, then the save fails and tools come back. @@ -773,13 +773,13 @@ describe( 'Cropper', () => { onGestureStart.mockClear(); // The next wheel zoom must open a gesture of its own. - fireEvent.wheel( canvas, { deltaY: -120, clientX: 100, clientY: 100 } ); + await userEvent.wheel( canvas, { delta: { y: -120 } } ); await waitFor( () => expect( onGestureStart ).toHaveBeenCalled() ); } ); it( 'ignores wheel zoom while disabled', async () => { const controller = createController(); - await render( + await renderCropper( { } ); const canvas = screen.getByRole( 'group', { name: 'Crop area' } ); - fireEvent.wheel( canvas, { deltaY: -120, clientX: 100, clientY: 100 } ); + const onWheel = vi.fn(); + canvas.addEventListener( 'wheel', onWheel, { once: true } ); + await userEvent.wheel( canvas, { delta: { y: -120 } } ); + await waitFor( () => expect( onWheel ).toHaveBeenCalledOnce() ); await act( async () => { await new Promise( ( resolve ) => @@ -808,7 +811,7 @@ describe( 'Cropper', () => { it( 'ignores keyboard pan while disabled', async () => { const controller = createController(); - await render( + await renderCropper( { ); const canvas = screen.getByRole( 'group', { name: 'Crop area' } ); - fireEvent.keyDown( canvas, { key: 'ArrowRight' } ); + canvas.focus(); + expect( canvas ).toHaveFocus(); + await userEvent.keyboard( '{ArrowRight}' ); expect( controller.setPan ).not.toHaveBeenCalled(); } ); diff --git a/packages/ui/src/form/primitives/control-with-error/test/control-with-error.browser.test.tsx b/packages/ui/src/form/primitives/control-with-error/test/control-with-error.browser.test.tsx new file mode 100644 index 00000000000000..cc2fddb40de20a --- /dev/null +++ b/packages/ui/src/form/primitives/control-with-error/test/control-with-error.browser.test.tsx @@ -0,0 +1,499 @@ +import { describe, expect, it, vi } from 'vitest'; +import { screen, waitFor, act } from '@testing-library/react'; +import { render } from 'vitest-browser-react'; +import { userEvent } from 'vitest/browser'; +import { + forwardRef, + useCallback, + useId, + useRef, + useState, +} from '@wordpress/element'; +import { useIsomorphicLayoutEffect } from '@wordpress/compose'; +import { ValidatedInputControl } from './fixtures/validated-input-control'; +import { ControlWithError } from '../index'; + +describe( 'ControlWithError', () => { + describe( 'label cloning', () => { + it( 'should pass string labels as strings when appending the required indicator', async () => { + await render( ); + + expect( screen.getByRole( 'textbox' ) ).toHaveAttribute( + 'aria-label', + 'Opacity (Required)' + ); + } ); + } ); + + describe( 'Reveal during pending validation', () => { + it( 'should keep the pending indicator instead of a native error on a synthetic `invalid` event', async () => { + const user = userEvent.setup(); + + function PendingValidatedInputControl() { + const ref = useRef< HTMLInputElement >( null ); + return ( + <> + + + + ); + } + + await render( ); + + await user.click( + screen.getByRole( 'button', { name: 'Show errors' } ) + ); + + await waitFor( () => { + expect( screen.getByText( 'Validating...' ) ).toBeVisible(); + } ); + expect( + screen.queryByText( 'Please fill out this field.' ) + ).not.toBeInTheDocument(); + } ); + } ); + + describe( 'Form submission', () => { + const CustomValidatedInputControl = ( { + ...restProps + }: React.ComponentProps< typeof ValidatedInputControl > ) => { + const [ customValidity, setCustomValidity ] = + useState< + React.ComponentProps< + typeof ValidatedInputControl + >[ 'customValidity' ] + >( undefined ); + return ( + + event.target.value === 'error' + ? setCustomValidity( { + type: 'invalid', + message: 'The word "error" is not allowed.', + } ) + : setCustomValidity( undefined ) + } + customValidity={ customValidity } + { ...restProps } + /> + ); + }; + + it( 'should show custom validity messages regardless of "touched" state if parent form is submitted', async () => { + const user = userEvent.setup(); + const onSubmit = vi.fn(); + await render( +
+ + + + ); + + const input = screen.getByRole< HTMLInputElement >( 'textbox', { + name: 'Text', + } ); + + // User has interacted, but not blurred + await user.type( input, 'error' ); + await user.keyboard( '{enter}' ); + + // Input is marked as invalid at the HTML level + await waitFor( () => { + expect( input.checkValidity() ).toBe( false ); + } ); + expect( input.validationMessage ).toBe( + 'The word "error" is not allowed.' + ); + + // Field is showing the error message + expect( + screen.getByText( 'The word "error" is not allowed.' ) + ).toBeVisible(); + + // Form is not submitted + expect( onSubmit ).not.toHaveBeenCalled(); + } ); + } ); + + describe( 'aria-describedby', () => { + it( 'should connect the error message to the input via aria-describedby', async () => { + const user = userEvent.setup(); + await render( +
+ + + + ); + + const input = screen.getByRole( 'textbox', { name: /^URL/ } ); + + expect( input ).not.toHaveAttribute( 'aria-describedby' ); + + await user.click( + screen.getByRole( 'button', { name: 'Submit' } ) + ); + + await waitFor( () => { + expect( input ).toHaveAccessibleDescription( + expect.stringContaining( 'Please fill out this field.' ) + ); + } ); + } ); + + it( 'should preserve existing aria-describedby values', async () => { + const user = userEvent.setup(); + + function TestComponent() { + const hintId = useId(); + return ( +
+ +

Enter a full URL.

+ + + ); + } + + await render( ); + + const input = screen.getByRole( 'textbox', { name: /^URL/ } ); + + expect( input ).toHaveAccessibleDescription( 'Enter a full URL.' ); + + await user.click( + screen.getByRole( 'button', { name: 'Submit' } ) + ); + + await waitFor( () => { + expect( input ).toHaveAccessibleDescription( + expect.stringContaining( 'Please fill out this field.' ) + ); + } ); + expect( input ).toHaveAccessibleDescription( + expect.stringContaining( 'Enter a full URL.' ) + ); + } ); + + it( 'should connect a custom validity error to the input via aria-describedby', async () => { + const user = userEvent.setup(); + + function TestComponent() { + const [ customValidity, setCustomValidity ] = + useState< + React.ComponentProps< + typeof ValidatedInputControl + >[ 'customValidity' ] + >( undefined ); + const inputRef = useRef< HTMLInputElement >( null ); + + return ( + <> + + + + ); + } + + await render( ); + + const input = screen.getByRole( 'textbox', { name: 'URL' } ); + expect( input ).not.toHaveAttribute( 'aria-describedby' ); + + await user.click( + screen.getByRole( 'button', { name: 'Validate' } ) + ); + + await waitFor( () => { + expect( input ).toHaveAccessibleDescription( + expect.stringContaining( 'Please enter a valid URL.' ) + ); + } ); + } ); + + it( 'should remove aria-describedby when the error is resolved', async () => { + const user = userEvent.setup(); + + function TestComponent() { + const [ customValidity, setCustomValidity ] = + useState< + React.ComponentProps< + typeof ValidatedInputControl + >[ 'customValidity' ] + >( undefined ); + const inputRef = useRef< HTMLInputElement >( null ); + + return ( + <> + + + + + ); + } + + await render( ); + + const input = screen.getByRole( 'textbox', { name: 'URL' } ); + + await user.click( + screen.getByRole( 'button', { name: 'Validate' } ) + ); + + await waitFor( () => { + expect( input ).toHaveAccessibleDescription( + expect.stringContaining( 'Please enter a valid URL.' ) + ); + } ); + + await user.click( screen.getByRole( 'button', { name: 'Clear' } ) ); + + await waitFor( () => { + expect( input ).not.toHaveAttribute( 'aria-describedby' ); + } ); + } ); + } ); + + describe( 'Controls that commit their value on blur', () => { + it( 'should clear a stale native error once the control commits a valid value on blur', async () => { + const user = userEvent.setup(); + + // Mimics controls like `NumberControl`: the value is clamped on + // blur, and the committed value is synced into the control's own + // state (and the DOM) in a layout effect, a render later. + const ClampedNumberInput = forwardRef< + HTMLInputElement, + { + label?: string; + value: string; + onChange: ( value: string ) => void; + } + >( function ClampedNumberInput( { label, value, onChange }, ref ) { + const [ innerValue, setInnerValue ] = useState( value ); + useIsomorphicLayoutEffect( () => { + setInnerValue( value ); + }, [ value ] ); + return ( + + setInnerValue( event.target.value ) + } + onBlur={ () => + onChange( + String( Math.max( 1, Number( innerValue ) ) ) + ) + } + /> + ); + } ); + + function Harness() { + const [ value, setValue ] = useState( '10' ); + const ref = useRef< HTMLInputElement >( null ); + const getValidityTarget = useCallback( () => ref.current, [] ); + return ( + + + + ); + } + + await render( ); + + const input = screen.getByRole< HTMLInputElement >( 'spinbutton', { + name: 'Number', + } ); + await user.clear( input ); + await user.type( input, '0' ); + // The message has to be showing before the blur for the assertion below + // to mean anything. Surface it the way a save action would, by validating + // the form while the field is still focused. + act( () => { + input.reportValidity(); + } ); + const validationMessage = input.validationMessage; + expect( validationMessage ).not.toBe( '' ); + expect( screen.getByText( validationMessage ) ).toBeVisible(); + + await user.tab(); + + await waitFor( () => { + expect( input ).toHaveValue( 1 ); + } ); + expect( + screen.queryByText( validationMessage ) + ).not.toBeInTheDocument(); + } ); + } ); + + describe( 'Focus behavior', () => { + it( 'should focus the first error in the form', async () => { + const user = userEvent.setup(); + await render( +
+ + + + + ); + + await user.click( + screen.getByRole( 'button', { name: 'Submit' } ) + ); + + expect( + screen.getByRole( 'textbox', { name: /^Text1/ } ) + ).toHaveFocus(); + } ); + + it( 'should focus the field on an `invalid` event, even if there is no enclosing form', async () => { + const user = userEvent.setup(); + function ValidatedInputControlWithRef( + props: React.ComponentProps< typeof ValidatedInputControl > + ) { + const ref = useRef< HTMLInputElement >( null ); + return ( + <> + + + + ); + } + + await render( + + ); + + await user.click( + screen.getByRole( 'button', { name: 'Report Validity' } ) + ); + + await waitFor( () => { + expect( + screen.getByRole( 'textbox', { name: /^Text/ } ) + ).toHaveFocus(); + } ); + } ); + + it( 'should show the error message without moving focus on a synthetic `invalid` event', async () => { + const user = userEvent.setup(); + function ValidatedInputControlWithRef( + props: React.ComponentProps< typeof ValidatedInputControl > + ) { + const ref = useRef< HTMLInputElement >( null ); + return ( + <> + + + + ); + } + + await render( + + ); + + const button = screen.getByRole( 'button', { + name: 'Show errors', + } ); + await user.click( button ); + + // The error message is revealed... + await waitFor( () => { + expect( + screen.getByText( 'Please fill out this field.' ) + ).toBeVisible(); + } ); + // ...but focus is not moved to the invalid field. + expect( button ).toHaveFocus(); + } ); + } ); +} ); diff --git a/packages/ui/src/form/primitives/control-with-error/test/control-with-error.jsdom.test.tsx b/packages/ui/src/form/primitives/control-with-error/test/control-with-error.jsdom.test.tsx index bd9ab018a87d73..7a7b87429e29aa 100644 --- a/packages/ui/src/form/primitives/control-with-error/test/control-with-error.jsdom.test.tsx +++ b/packages/ui/src/form/primitives/control-with-error/test/control-with-error.jsdom.test.tsx @@ -1,73 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { - render, - screen, - waitFor, - act, - fireEvent, -} from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { - forwardRef, - useCallback, - useId, - useRef, - useState, -} from '@wordpress/element'; -import { useIsomorphicLayoutEffect, useMergeRefs } from '@wordpress/compose'; -import { ControlWithError } from '../index'; - -const ValidatedInput = forwardRef< - HTMLInputElement, - React.InputHTMLAttributes< HTMLInputElement > & { label?: string } ->( function ValidatedInput( { label, ...restProps }, ref ) { - return ; -} ); - -type ValidatedInputControlProps = React.ComponentProps< - typeof ValidatedInput -> & - Pick< - React.ComponentProps< typeof ControlWithError >, - 'required' | 'markWhenOptional' | 'customValidity' - >; - -const ValidatedInputControl = forwardRef< - HTMLInputElement, - ValidatedInputControlProps ->( function ValidatedInputControl( - { required, markWhenOptional, customValidity, ...restProps }, - forwardedRef -) { - const validityTargetRef = useRef< HTMLInputElement >( null ); - const mergedRefs = useMergeRefs( [ forwardedRef, validityTargetRef ] ); - - return ( - validityTargetRef.current } - > - - - ); -} ); +import { render, screen, act, fireEvent } from '@testing-library/react'; +import { useCallback, useState } from '@wordpress/element'; +import { ValidatedInputControl } from './fixtures/validated-input-control'; globalThis.wpVitest.mockMatchMedia(); describe( 'ControlWithError', () => { - describe( 'label cloning', () => { - it( 'should pass string labels as strings when appending the required indicator', () => { - render( ); - - expect( screen.getByRole( 'textbox' ) ).toHaveAttribute( - 'aria-label', - 'Opacity (Required)' - ); - } ); - } ); - describe( 'Async Validation', () => { beforeEach( () => { vi.useFakeTimers( { @@ -245,472 +183,4 @@ describe( 'ControlWithError', () => { ).toBeVisible(); } ); } ); - - describe( 'Reveal during pending validation', () => { - it( 'should keep the pending indicator instead of a native error on a synthetic `invalid` event', async () => { - const user = userEvent.setup(); - - function PendingValidatedInputControl() { - const ref = useRef< HTMLInputElement >( null ); - return ( - <> - - - - ); - } - - render( ); - - await user.click( - screen.getByRole( 'button', { name: 'Show errors' } ) - ); - - await waitFor( () => { - expect( screen.getByText( 'Validating...' ) ).toBeVisible(); - } ); - expect( - screen.queryByText( 'Constraints not satisfied' ) - ).not.toBeInTheDocument(); - } ); - } ); - - describe( 'Form submission', () => { - const CustomValidatedInputControl = ( { - ...restProps - }: React.ComponentProps< typeof ValidatedInputControl > ) => { - const [ customValidity, setCustomValidity ] = - useState< - React.ComponentProps< - typeof ValidatedInputControl - >[ 'customValidity' ] - >( undefined ); - return ( - - event.target.value === 'error' - ? setCustomValidity( { - type: 'invalid', - message: 'The word "error" is not allowed.', - } ) - : setCustomValidity( undefined ) - } - customValidity={ customValidity } - { ...restProps } - /> - ); - }; - - it( 'should show custom validity messages regardless of "touched" state if parent form is submitted', async () => { - const user = userEvent.setup(); - const onSubmit = vi.fn(); - render( -
- - - - ); - - const input = screen.getByRole< HTMLInputElement >( 'textbox', { - name: 'Text', - } ); - - // User has interacted, but not blurred - await user.type( input, 'error' ); - await user.keyboard( '{enter}' ); - - // Input is marked as invalid at the HTML level - await waitFor( () => { - expect( input.checkValidity() ).toBe( false ); - } ); - expect( input.validationMessage ).toBe( - 'The word "error" is not allowed.' - ); - - // Field is showing the error message - expect( - screen.getByText( 'The word "error" is not allowed.' ) - ).toBeVisible(); - - // Form is not submitted - expect( onSubmit ).not.toHaveBeenCalled(); - } ); - } ); - - describe( 'aria-describedby', () => { - it( 'should connect the error message to the input via aria-describedby', async () => { - const user = userEvent.setup(); - render( -
- - - - ); - - const input = screen.getByRole( 'textbox', { name: /^URL/ } ); - - expect( input ).not.toHaveAttribute( 'aria-describedby' ); - - await user.click( - screen.getByRole( 'button', { name: 'Submit' } ) - ); - - await waitFor( () => { - expect( input ).toHaveAccessibleDescription( - expect.stringContaining( 'Constraints not satisfied' ) - ); - } ); - } ); - - it( 'should preserve existing aria-describedby values', async () => { - const user = userEvent.setup(); - - function TestComponent() { - const hintId = useId(); - return ( -
- -

Enter a full URL.

- - - ); - } - - render( ); - - const input = screen.getByRole( 'textbox', { name: /^URL/ } ); - - expect( input ).toHaveAccessibleDescription( 'Enter a full URL.' ); - - await user.click( - screen.getByRole( 'button', { name: 'Submit' } ) - ); - - await waitFor( () => { - expect( input ).toHaveAccessibleDescription( - expect.stringContaining( 'Constraints not satisfied' ) - ); - } ); - expect( input ).toHaveAccessibleDescription( - expect.stringContaining( 'Enter a full URL.' ) - ); - } ); - - it( 'should connect a custom validity error to the input via aria-describedby', async () => { - const user = userEvent.setup(); - - function TestComponent() { - const [ customValidity, setCustomValidity ] = - useState< - React.ComponentProps< - typeof ValidatedInputControl - >[ 'customValidity' ] - >( undefined ); - const inputRef = useRef< HTMLInputElement >( null ); - - return ( - <> - - - - ); - } - - render( ); - - const input = screen.getByRole( 'textbox', { name: 'URL' } ); - expect( input ).not.toHaveAttribute( 'aria-describedby' ); - - await user.click( - screen.getByRole( 'button', { name: 'Validate' } ) - ); - - await waitFor( () => { - expect( input ).toHaveAccessibleDescription( - expect.stringContaining( 'Please enter a valid URL.' ) - ); - } ); - } ); - - it( 'should remove aria-describedby when the error is resolved', async () => { - const user = userEvent.setup(); - - function TestComponent() { - const [ customValidity, setCustomValidity ] = - useState< - React.ComponentProps< - typeof ValidatedInputControl - >[ 'customValidity' ] - >( undefined ); - const inputRef = useRef< HTMLInputElement >( null ); - - return ( - <> - - - - - ); - } - - render( ); - - const input = screen.getByRole( 'textbox', { name: 'URL' } ); - - await user.click( - screen.getByRole( 'button', { name: 'Validate' } ) - ); - - await waitFor( () => { - expect( input ).toHaveAccessibleDescription( - expect.stringContaining( 'Please enter a valid URL.' ) - ); - } ); - - await user.click( screen.getByRole( 'button', { name: 'Clear' } ) ); - - await waitFor( () => { - expect( input ).not.toHaveAttribute( 'aria-describedby' ); - } ); - } ); - } ); - - describe( 'Controls that commit their value on blur', () => { - it( 'should clear a stale native error once the control commits a valid value on blur', async () => { - const user = userEvent.setup(); - - // Mimics controls like `NumberControl`: the value is clamped on - // blur, and the committed value is synced into the control's own - // state (and the DOM) in a layout effect, a render later. - const ClampedNumberInput = forwardRef< - HTMLInputElement, - { - label?: string; - value: string; - onChange: ( value: string ) => void; - } - >( function ClampedNumberInput( { label, value, onChange }, ref ) { - const [ innerValue, setInnerValue ] = useState( value ); - useIsomorphicLayoutEffect( () => { - setInnerValue( value ); - }, [ value ] ); - return ( - - setInnerValue( event.target.value ) - } - onBlur={ () => - onChange( - String( Math.max( 1, Number( innerValue ) ) ) - ) - } - /> - ); - } ); - - function Harness() { - const [ value, setValue ] = useState( '10' ); - const ref = useRef< HTMLInputElement >( null ); - const getValidityTarget = useCallback( () => ref.current, [] ); - return ( - - - - ); - } - - render( ); - - const input = screen.getByRole< HTMLInputElement >( 'spinbutton', { - name: 'Number', - } ); - await user.clear( input ); - await user.type( input, '0' ); - // The message has to be showing before the blur for the assertion below - // to mean anything. Surface it the way a save action would, by validating - // the form while the field is still focused. - act( () => { - input.reportValidity(); - } ); - expect( - screen.getByText( 'Constraints not satisfied' ) - ).toBeVisible(); - - await user.tab(); - - await waitFor( () => { - expect( input ).toHaveValue( 1 ); - } ); - expect( - screen.queryByText( 'Constraints not satisfied' ) - ).not.toBeInTheDocument(); - } ); - } ); - - describe( 'Focus behavior', () => { - it( 'should focus the first error in the form', async () => { - const user = userEvent.setup(); - render( -
- - - - - ); - - await user.click( - screen.getByRole( 'button', { name: 'Submit' } ) - ); - - expect( - screen.getByRole( 'textbox', { name: /^Text1/ } ) - ).toHaveFocus(); - } ); - - it( 'should focus the field on an `invalid` event, even if there is no enclosing form', async () => { - const user = userEvent.setup(); - function ValidatedInputControlWithRef( - props: React.ComponentProps< typeof ValidatedInputControl > - ) { - const ref = useRef< HTMLInputElement >( null ); - return ( - <> - - - - ); - } - - render( ); - - await user.click( - screen.getByRole( 'button', { name: 'Report Validity' } ) - ); - - await waitFor( () => { - expect( - screen.getByRole( 'textbox', { name: /^Text/ } ) - ).toHaveFocus(); - } ); - } ); - - it( 'should show the error message without moving focus on a synthetic `invalid` event', async () => { - const user = userEvent.setup(); - function ValidatedInputControlWithRef( - props: React.ComponentProps< typeof ValidatedInputControl > - ) { - const ref = useRef< HTMLInputElement >( null ); - return ( - <> - - - - ); - } - - render( ); - - const button = screen.getByRole( 'button', { - name: 'Show errors', - } ); - await user.click( button ); - - // The error message is revealed... - await waitFor( () => { - expect( - screen.getByText( 'Constraints not satisfied' ) - ).toBeVisible(); - } ); - // ...but focus is not moved to the invalid field. - expect( button ).toHaveFocus(); - } ); - } ); } ); diff --git a/packages/ui/src/form/primitives/control-with-error/test/fixtures/validated-input-control.tsx b/packages/ui/src/form/primitives/control-with-error/test/fixtures/validated-input-control.tsx new file mode 100644 index 00000000000000..c01fed3d26cdd0 --- /dev/null +++ b/packages/ui/src/form/primitives/control-with-error/test/fixtures/validated-input-control.tsx @@ -0,0 +1,40 @@ +import { forwardRef, useRef } from '@wordpress/element'; +import { useMergeRefs } from '@wordpress/compose'; +import { ControlWithError } from '../../index'; + +const ValidatedInput = forwardRef< + HTMLInputElement, + React.InputHTMLAttributes< HTMLInputElement > & { label?: string } +>( function ValidatedInput( { label, ...restProps }, ref ) { + return ; +} ); + +type ValidatedInputControlProps = React.ComponentProps< + typeof ValidatedInput +> & + Pick< + React.ComponentProps< typeof ControlWithError >, + 'required' | 'markWhenOptional' | 'customValidity' + >; + +export const ValidatedInputControl = forwardRef< + HTMLInputElement, + ValidatedInputControlProps +>( function ValidatedInputControl( + { required, markWhenOptional, customValidity, ...restProps }, + forwardedRef +) { + const validityTargetRef = useRef< HTMLInputElement >( null ); + const mergedRefs = useMergeRefs( [ forwardedRef, validityTargetRef ] ); + + return ( + validityTargetRef.current } + > + + + ); +} ); diff --git a/packages/ui/src/utils/test/use-overlay-scroll-state-attributes.browser.test.tsx b/packages/ui/src/utils/test/use-overlay-scroll-state-attributes.browser.test.tsx index 0de80c981c309d..e8b156a666fed4 100644 --- a/packages/ui/src/utils/test/use-overlay-scroll-state-attributes.browser.test.tsx +++ b/packages/ui/src/utils/test/use-overlay-scroll-state-attributes.browser.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { screen, waitFor } from '@testing-library/react'; import { render } from 'vitest-browser-react'; import { describe, expect, it, vi } from 'vitest'; import { useOverlayScrollStateAttributes } from '../use-overlay-scroll-state-attributes'; @@ -43,19 +43,16 @@ describe( 'useOverlayScrollStateAttributes browser layout', () => { ); container.scrollTop = 100; - fireEvent.scroll( container ); - + await waitFor( () => expect( onScroll ).toHaveBeenCalledTimes( 1 ) ); expect( container ).toHaveAttribute( 'data-wp-ui-overlay-scrolled-from-top' ); expect( container ).toHaveAttribute( 'data-wp-ui-overlay-scrolled-from-bottom' ); - expect( onScroll ).toHaveBeenCalledTimes( 1 ); container.scrollTop = container.scrollHeight; - fireEvent.scroll( container ); - + await waitFor( () => expect( onScroll ).toHaveBeenCalledTimes( 2 ) ); expect( container ).toHaveAttribute( 'data-wp-ui-overlay-scrolled-from-top' ); diff --git a/test/unit/VITEST_MIGRATION.md b/test/unit/VITEST_MIGRATION.md index 2be5a1aa2b8ef2..75d0c2173f1b8c 100644 --- a/test/unit/VITEST_MIGRATION.md +++ b/test/unit/VITEST_MIGRATION.md @@ -37,6 +37,11 @@ When writing or migrating a test: structure, and deterministic DOM semantics, events, and state. Browser API exceptions require a concrete reason and must not remain after the exception is no longer needed. + Prefer real browser behavior over an exception for component interaction + and layout tests. Supplied rectangles, observer notifications, and timers + can remain in JSDOM when they are deliberate inputs to algorithm or + lifecycle tests. A browser API in test setup alone does not establish that + the assertions need Browser Mode. - Before running Browser Mode tests locally for the first time, install Chromium with `npm exec --no --workspace @wordpress/unit-tests -- playwright install chromium`. diff --git a/test/unit/vitest-policy-exceptions.json b/test/unit/vitest-policy-exceptions.json index 77ed0fd03650f9..b8bcc46bd7a363 100644 --- a/test/unit/vitest-policy-exceptions.json +++ b/test/unit/vitest-policy-exceptions.json @@ -1,23 +1,13 @@ { "browserFireEvent": { - "packages/components/src/color-picker/test/index.browser.test.tsx": "Uses exact pointer and mouse coordinates to verify visual picker geometry and a complete pointer lifecycle that native userEvent cannot express deterministically.", - "packages/components/src/custom-gradient-picker/test/index.browser.test.tsx": "Uses exact mouse coordinates to verify gradient marker positioning while observable clicks and keyboard input use native userEvent.", - "packages/components/src/focal-point-picker/test/index.browser.test.tsx": "Uses exact mouse coordinates and an explicit blur sequence to verify drag lifecycle state that native userEvent cannot express deterministically.", - "packages/dataviews/src/dataviews/test/infinite-scroll.browser.test.tsx": "Sets controlled scroll metrics before dispatching scroll to verify the infinite-loading threshold deterministically.", + "packages/components/src/focal-point-picker/test/index.browser.test.tsx": "Starts an unreleased mouse gesture to verify cancellation when native Tab moves focus away; subsequent movement uses native hover.", "packages/media-editor/src/image-editor/react/components/stencils/test/rectangle-stencil.browser.test.tsx": "Uses exact pointer and touch payloads for capture lifecycle coverage, plus direct key events only where fake timers verify resize debounce timing.", - "packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx": "Uses exact pointer, wheel, and transition payloads for crop geometry and lifecycle coverage, plus a direct key event only where fake timers isolate resize timing.", - "packages/ui/src/utils/test/use-overlay-scroll-state-attributes.browser.test.tsx": "Sets controlled scroll dimensions before dispatching scroll to verify overlay state transitions deterministically." + "packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx": "Uses exact pointer, wheel, and transition payloads for crop geometry and lifecycle coverage, plus a direct key event only where fake timers isolate resize timing." }, "jsdomBrowserApis": { "test/unit/config/setup-globals.vitest.jsdom.test.js": "This infrastructure regression must exercise the opt-in matchMedia mock in the jsdom project that installs it.", "packages/block-editor/src/utils/test/dom.jsdom.test.jsx": "Uses explicit DOMRect fixtures to test clipping and element-selection algorithms without relying on browser layout.", - "packages/components/src/validated-form-controls/test/range-control.jsdom.test.tsx": "Uses requestAnimationFrame only to schedule reportValidity after React state; assertions cover accessible description semantics.", - "packages/grid/src/dashboard-grid/test/item-interactions.jsdom.test.tsx": "Stubs ResizeObserver only to mount the grid; assertions cover deterministic drag and resize control semantics.", - "packages/grid/src/dashboard-grid/test/keyboard-activation.jsdom.test.tsx": "Stubs ResizeObserver only to mount the grid; assertions cover the deterministic keyboard activator DOM hierarchy.", - "packages/grid/src/dashboard-lanes/test/item-interactions.jsdom.test.tsx": "Stubs ResizeObserver only to mount the lanes; assertions cover deterministic drag and resize control semantics.", - "packages/grid/src/dashboard-lanes/test/keyboard-activation.jsdom.test.tsx": "Stubs ResizeObserver only to mount the lanes; assertions cover the deterministic keyboard activator DOM hierarchy.", "packages/grid/src/dashboard-lanes/test/use-lane-placement.jsdom.test.tsx": "Injects ResizeObserver entries and requestAnimationFrame scheduling to test deterministic lane-placement state without browser layout.", - "packages/ui/src/form/primitives/control-with-error/test/control-with-error.jsdom.test.tsx": "Uses requestAnimationFrame only to schedule reportValidity after React state; assertions cover aria-describedby semantics.", "packages/editor/src/components/collab-sidebar/test/board-store.jsdom.test.js": "Uses supplied DOMRect fixtures to test deterministic range-to-anchor calculations without relying on rendered layout.", "packages/ui/src/breadcrumb/test/index.jsdom.test.tsx": "Injects sizes, ResizeObserver notifications, font readiness, and animation frames to verify deterministic overflow state and measurement lifecycle. Real responsive layout is covered in index.browser.test.tsx." } From 9d323deac6628f33dde6b4409b29edefc629f996 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Thu, 10 Sep 2026 22:47:25 +0200 Subject: [PATCH 4/5] Test: Preserve picker coverage and detect browser API mocks --- .../color-picker/test/index.browser.test.tsx | 13 +++-- .../test/index.browser.test.tsx | 9 +++- test/unit/VITEST_MIGRATION.md | 2 + .../scripts/test/vitest-policy-rules.test.js | 30 +++++++++--- test/unit/scripts/vitest-policy-rules.mjs | 48 ++++++++++++++----- test/unit/vitest-policy-exceptions.json | 8 +++- 6 files changed, 83 insertions(+), 27 deletions(-) diff --git a/packages/components/src/color-picker/test/index.browser.test.tsx b/packages/components/src/color-picker/test/index.browser.test.tsx index adc17ca4242132..b4fbc55111a77c 100644 --- a/packages/components/src/color-picker/test/index.browser.test.tsx +++ b/packages/components/src/color-picker/test/index.browser.test.tsx @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import { userEvent } from 'vitest/browser'; -import { screen, waitFor } from '@testing-library/react'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; import { render } from 'vitest-browser-react'; import { useState } from '@wordpress/element'; import { ColorPicker } from '..'; @@ -695,8 +695,15 @@ describe( 'ColorPicker', () => { ) as HTMLElement; expect( parseFloat( pointer.style.left ) ).toBeGreaterThan( 50 ); - // Drag to the bottom of the saturation surface at 80% saturation. - await dragToBlack( interactive ); + // Exact black is on the lower boundary, outside the native hit area. + // Supply that coordinate without movement to retain click-only coverage. + const bounds = interactive.getBoundingClientRect(); + fireEvent.mouseDown( interactive, { + clientX: bounds.left + bounds.width * 0.8, + clientY: bounds.bottom, + buttons: 1, + } ); + fireEvent.mouseUp( interactive ); expectPointerPosition( pointer, { top: 100 } ); // Lossy HSVA→HSLA→HSVA sync would snap left to 0%. diff --git a/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx b/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx index 1fa3b55b07fe51..04a14ecd9a74a8 100644 --- a/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx +++ b/packages/components/src/custom-gradient-picker/test/index.browser.test.tsx @@ -3,9 +3,14 @@ import { userEvent } from 'vitest/browser'; import { screen, waitFor } from '@testing-library/react'; import { render } from 'vitest-browser-react'; import { useState } from '@wordpress/element'; -// Load the picker, buttons and portaled popover as a consumer does. // eslint-disable-next-line @wordpress/no-non-module-stylesheet-imports -import '../../style.scss'; +import '../style.scss'; +// eslint-disable-next-line @wordpress/no-non-module-stylesheet-imports +import '../../button/style.scss'; +// eslint-disable-next-line @wordpress/no-non-module-stylesheet-imports +import '../../dropdown/style.scss'; +// eslint-disable-next-line @wordpress/no-non-module-stylesheet-imports +import '../../popover/style.scss'; import CustomGradientPicker from '../'; import CustomGradientBar from '../gradient-bar'; import { KEYBOARD_CONTROL_POINT_VARIATION } from '../gradient-bar/constants'; diff --git a/test/unit/VITEST_MIGRATION.md b/test/unit/VITEST_MIGRATION.md index 75d0c2173f1b8c..1a3aa04b60ad54 100644 --- a/test/unit/VITEST_MIGRATION.md +++ b/test/unit/VITEST_MIGRATION.md @@ -37,11 +37,13 @@ When writing or migrating a test: structure, and deterministic DOM semantics, events, and state. Browser API exceptions require a concrete reason and must not remain after the exception is no longer needed. + Prefer real browser behavior over an exception for component interaction and layout tests. Supplied rectangles, observer notifications, and timers can remain in JSDOM when they are deliberate inputs to algorithm or lifecycle tests. A browser API in test setup alone does not establish that the assertions need Browser Mode. + - Before running Browser Mode tests locally for the first time, install Chromium with `npm exec --no --workspace @wordpress/unit-tests -- playwright install chromium`. diff --git a/test/unit/scripts/test/vitest-policy-rules.test.js b/test/unit/scripts/test/vitest-policy-rules.test.js index 163dfe1160fe25..ca472f1480c5ae 100644 --- a/test/unit/scripts/test/vitest-policy-rules.test.js +++ b/test/unit/scripts/test/vitest-policy-rules.test.js @@ -88,13 +88,22 @@ describe( 'Vitest policy rules', () => { } ); it( 'rejects jsdom browser APIs without a reason', () => { - const source = 'new ResizeObserver( () => {} );'; - - expectViolation( source, 'require Browser Mode', { project: 'jsdom' } ); - expectValid( source, { - allowJsdomBrowserApis: true, - project: 'jsdom', - } ); + for ( const source of [ + 'new ResizeObserver( () => {} );', + "import { vi } from 'vitest'; vi.stubGlobal( 'ResizeObserver', class {} );", + "import { vi as mocker } from 'vitest'; mocker.stubGlobal( 'innerWidth', 320 );", + "import * as vitest from 'vitest'; vitest.vi.spyOn( HTMLElement.prototype, 'getBoundingClientRect' );", + "import { vi } from 'vitest'; vi.spyOn( window, 'matchMedia' );", + "import { vi } from 'vitest'; const element = document.createElement( 'div' ); vi.spyOn( element, 'offsetWidth', 'get' );", + ] ) { + expectViolation( source, 'require Browser Mode', { + project: 'jsdom', + } ); + expectValid( source, { + allowJsdomBrowserApis: true, + project: 'jsdom', + } ); + } } ); it( 'allows type-only jsdom browser API references', () => { @@ -114,6 +123,13 @@ describe( 'Vitest policy rules', () => { 'const fake = { scrollTop: 0 };\nfake.scrollTop;\nconst mockLayout = { getBoundingClientRect() {} };\nmockLayout.getBoundingClientRect();', { project: 'jsdom' } ); + for ( const source of [ + "import { vi } from 'vitest'; const fake = { getBoundingClientRect() {} }; vi.spyOn( fake, 'getBoundingClientRect' );", + "import { vi } from 'vitest'; vi.stubGlobal( 'fetch', () => {} );", + "const vi = { stubGlobal() {}, spyOn() {} }; vi.stubGlobal( 'ResizeObserver', class {} ); vi.spyOn( HTMLElement.prototype, 'getBoundingClientRect' );", + ] ) { + expectValid( source, { project: 'jsdom' } ); + } } ); it( 'rejects animation APIs on DOM-derived jsdom objects', () => { diff --git a/test/unit/scripts/vitest-policy-rules.mjs b/test/unit/scripts/vitest-policy-rules.mjs index 654a0ebce5c78f..176a20b4f89f16 100644 --- a/test/unit/scripts/vitest-policy-rules.mjs +++ b/test/unit/scripts/vitest-policy-rules.mjs @@ -2305,22 +2305,43 @@ export function validateVitestPolicy( { ); } - if ( - project === 'jsdom' && - ! typeOnlyNodes.has( node ) && - ( ( node.type === 'Identifier' && - browserApiIdentifiers.has( node.name ) && - unboundIdentifiers.has( node ) ) || - ( node.type === 'MemberExpression' && - browserApiProperties.has( getMemberPropertyName( node ) ) && + if ( project === 'jsdom' && ! typeOnlyNodes.has( node ) ) { + const isVitestMock = + node.type === 'CallExpression' && + node.callee?.type === 'MemberExpression' && + isImportedApiReference( + node.callee.object, + 'vi', + vitestViVariables, + vitestNamespaceVariables, + identifierVariables + ); + const mockMethod = + isVitestMock && getMemberPropertyName( node.callee ); + const apiName = + mockMethod === 'spyOn' + ? getStaticStringValue( node.arguments[ 1 ] ) + : getMemberPropertyName( node ); + const apiTarget = + mockMethod === 'spyOn' ? node.arguments[ 0 ] : node.object; + + if ( + ( node.type === 'Identifier' && + browserApiIdentifiers.has( node.name ) && + unboundIdentifiers.has( node ) ) || + ( mockMethod === 'stubGlobal' && + browserApiProperties.has( + getStaticStringValue( node.arguments[ 0 ] ) + ) ) || + ( browserApiProperties.has( apiName ) && ( isWindowReference( - node.object, + apiTarget, unboundIdentifiers, windowVariables, identifierVariables ) || isBrowserGlobalExpression( - node.object, + apiTarget, unboundIdentifiers, domVariables, domCollectionVariables, @@ -2332,9 +2353,10 @@ export function validateVitestPolicy( { testingLibraryCollectionFunctionVariables, testingLibraryAsyncCollectionFunctionVariables, testingLibraryNamespaceVariables - ) ) ) ) - ) { - reportJsdomBrowserApi( node ); + ) ) ) + ) { + reportJsdomBrowserApi( node ); + } } if ( diff --git a/test/unit/vitest-policy-exceptions.json b/test/unit/vitest-policy-exceptions.json index b8bcc46bd7a363..016823f7a5d3f6 100644 --- a/test/unit/vitest-policy-exceptions.json +++ b/test/unit/vitest-policy-exceptions.json @@ -2,13 +2,17 @@ "browserFireEvent": { "packages/components/src/focal-point-picker/test/index.browser.test.tsx": "Starts an unreleased mouse gesture to verify cancellation when native Tab moves focus away; subsequent movement uses native hover.", "packages/media-editor/src/image-editor/react/components/stencils/test/rectangle-stencil.browser.test.tsx": "Uses exact pointer and touch payloads for capture lifecycle coverage, plus direct key events only where fake timers verify resize debounce timing.", - "packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx": "Uses exact pointer, wheel, and transition payloads for crop geometry and lifecycle coverage, plus a direct key event only where fake timers isolate resize timing." + "packages/media-editor/src/image-editor/react/components/test/cropper.browser.test.tsx": "Uses exact pointer, wheel, and transition payloads for crop geometry and lifecycle coverage, plus a direct key event only where fake timers isolate resize timing.", + "packages/components/src/color-picker/test/index.browser.test.tsx": "Supplies exact bottom-edge mouse coordinates for click-to-black saturation coverage, where native hit testing excludes the lower boundary. Drag and keyboard paths use native input." }, "jsdomBrowserApis": { "test/unit/config/setup-globals.vitest.jsdom.test.js": "This infrastructure regression must exercise the opt-in matchMedia mock in the jsdom project that installs it.", "packages/block-editor/src/utils/test/dom.jsdom.test.jsx": "Uses explicit DOMRect fixtures to test clipping and element-selection algorithms without relying on browser layout.", "packages/grid/src/dashboard-lanes/test/use-lane-placement.jsdom.test.tsx": "Injects ResizeObserver entries and requestAnimationFrame scheduling to test deterministic lane-placement state without browser layout.", "packages/editor/src/components/collab-sidebar/test/board-store.jsdom.test.js": "Uses supplied DOMRect fixtures to test deterministic range-to-anchor calculations without relying on rendered layout.", - "packages/ui/src/breadcrumb/test/index.jsdom.test.tsx": "Injects sizes, ResizeObserver notifications, font readiness, and animation frames to verify deterministic overflow state and measurement lifecycle. Real responsive layout is covered in index.browser.test.tsx." + "packages/ui/src/breadcrumb/test/index.jsdom.test.tsx": "Injects sizes, ResizeObserver notifications, font readiness, and animation frames to verify deterministic overflow state and measurement lifecycle. Real responsive layout is covered in index.browser.test.tsx.", + "packages/grid/src/dashboard-grid/test/item-limits.jsdom.test.tsx": "Supplies fixed tile rectangles and timers to verify minimum-size quantization and stored layout updates independently of browser layout.", + "packages/grid/src/dashboard-lanes/test/item-limits.jsdom.test.tsx": "Supplies two container geometries and timers to verify lane-width quantization and minimum-size clamping independently of browser layout.", + "packages/components/src/custom-gradient-picker/gradient-bar/test/utils.jsdom.test.ts": "Supplies fixed rectangles to verify coordinate-to-percentage conversion, rounding, and clamping without relying on browser layout." } } From 2c83303010e014db7d24d1c2b86cf46af7c4dbd9 Mon Sep 17 00:00:00 2001 From: Marco Ciampini Date: Fri, 11 Sep 2026 09:56:59 +0200 Subject: [PATCH 5/5] Test: Track jsdom geometry in local helpers --- .../scripts/test/vitest-policy-rules.test.js | 9 +++ test/unit/scripts/vitest-policy-rules.mjs | 59 ++++++++++++++----- test/unit/vitest-policy-exceptions.json | 1 + 3 files changed, 53 insertions(+), 16 deletions(-) diff --git a/test/unit/scripts/test/vitest-policy-rules.test.js b/test/unit/scripts/test/vitest-policy-rules.test.js index ca472f1480c5ae..83e5baf5ee9666 100644 --- a/test/unit/scripts/test/vitest-policy-rules.test.js +++ b/test/unit/scripts/test/vitest-policy-rules.test.js @@ -125,6 +125,7 @@ describe( 'Vitest policy rules', () => { ); for ( const source of [ "import { vi } from 'vitest'; const fake = { getBoundingClientRect() {} }; vi.spyOn( fake, 'getBoundingClientRect' );", + "import { vi } from 'vitest'; function mockRect( value ) { vi.spyOn( value, 'getBoundingClientRect' ); } const fake = { getBoundingClientRect() {} }; mockRect( fake );", "import { vi } from 'vitest'; vi.stubGlobal( 'fetch', () => {} );", "const vi = { stubGlobal() {}, spyOn() {} }; vi.stubGlobal( 'ResizeObserver', class {} ); vi.spyOn( HTMLElement.prototype, 'getBoundingClientRect' );", ] ) { @@ -154,6 +155,14 @@ describe( 'Vitest policy rules', () => { } } ); + it( 'tracks DOM values through local helper parameters', () => { + expectViolation( + "import { vi } from 'vitest';\nfunction mockRect( element ) { vi.spyOn( element, 'getBoundingClientRect' ); }\nconst element = document.createElement( 'div' );\nmockRect( element );", + 'require Browser Mode', + { project: 'jsdom' } + ); + } ); + it( 'tracks Testing Library DOM results and later assignments', () => { for ( const source of [ "import { screen } from '@testing-library/react';\nscreen.getByRole( 'button' ).getBoundingClientRect();", diff --git a/test/unit/scripts/vitest-policy-rules.mjs b/test/unit/scripts/vitest-policy-rules.mjs index 176a20b4f89f16..b06655e451e504 100644 --- a/test/unit/scripts/vitest-policy-rules.mjs +++ b/test/unit/scripts/vitest-policy-rules.mjs @@ -1611,6 +1611,21 @@ export function validateVitestPolicy( { } } }; + const isTrackedDomValue = ( value ) => + isBrowserGlobalExpression( + value, + unboundIdentifiers, + domVariables, + domCollectionVariables, + identifierVariables, + windowVariables, + testingLibraryScreenVariables, + testingLibraryDomFunctionVariables, + testingLibraryAsyncDomFunctionVariables, + testingLibraryCollectionFunctionVariables, + testingLibraryAsyncCollectionFunctionVariables, + testingLibraryNamespaceVariables + ); for ( const node of ast.body ) { if ( node.type !== 'ImportDeclaration' ) { @@ -1834,6 +1849,33 @@ export function validateVitestPolicy( { } } + if ( node.type === 'CallExpression' ) { + let localFunctions; + for ( const [ + argumentIndex, + argument, + ] of node.arguments.entries() ) { + if ( + argument.type !== 'SpreadElement' && + isTrackedDomValue( argument ) + ) { + localFunctions ??= getReachableLocalFunctions( + node.callee, + identifierVariables, + parentNodes + ); + for ( const localFunction of localFunctions ) { + trackDomValuePattern( + localFunction.functionNode.params[ + argumentIndex + + localFunction.boundArgumentCount + ] + ); + } + } + } + } + const { target, value, isCollectionElement } = getTrackedAssignment( node ); @@ -2096,22 +2138,7 @@ export function validateVitestPolicy( { } } - if ( - ! isBrowserGlobalExpression( - value, - unboundIdentifiers, - domVariables, - domCollectionVariables, - identifierVariables, - windowVariables, - testingLibraryScreenVariables, - testingLibraryDomFunctionVariables, - testingLibraryAsyncDomFunctionVariables, - testingLibraryCollectionFunctionVariables, - testingLibraryAsyncCollectionFunctionVariables, - testingLibraryNamespaceVariables - ) - ) { + if ( ! isTrackedDomValue( value ) ) { return; } diff --git a/test/unit/vitest-policy-exceptions.json b/test/unit/vitest-policy-exceptions.json index 016823f7a5d3f6..2d70e0f0f887ed 100644 --- a/test/unit/vitest-policy-exceptions.json +++ b/test/unit/vitest-policy-exceptions.json @@ -10,6 +10,7 @@ "packages/block-editor/src/utils/test/dom.jsdom.test.jsx": "Uses explicit DOMRect fixtures to test clipping and element-selection algorithms without relying on browser layout.", "packages/grid/src/dashboard-lanes/test/use-lane-placement.jsdom.test.tsx": "Injects ResizeObserver entries and requestAnimationFrame scheduling to test deterministic lane-placement state without browser layout.", "packages/editor/src/components/collab-sidebar/test/board-store.jsdom.test.js": "Uses supplied DOMRect fixtures to test deterministic range-to-anchor calculations without relying on rendered layout.", + "packages/editor/src/components/collaborators-overlay/test/cursor-dom-utils.jsdom.test.ts": "Supplies fixed element and range rectangles to verify cursor fallback and ancestor-selection algorithms without relying on browser layout.", "packages/ui/src/breadcrumb/test/index.jsdom.test.tsx": "Injects sizes, ResizeObserver notifications, font readiness, and animation frames to verify deterministic overflow state and measurement lifecycle. Real responsive layout is covered in index.browser.test.tsx.", "packages/grid/src/dashboard-grid/test/item-limits.jsdom.test.tsx": "Supplies fixed tile rectangles and timers to verify minimum-size quantization and stored layout updates independently of browser layout.", "packages/grid/src/dashboard-lanes/test/item-limits.jsdom.test.tsx": "Supplies two container geometries and timers to verify lane-width quantization and minimum-size clamping independently of browser layout.",