An open source design system that's fully customizable and agent ready
TypeScript
test: module loads are awaited, not raced against test clocks (#9447)
Christopher Chedeaub53bec615429
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSheetFirstOpen.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSheetFirstOpen.test.tsxindex 6b0e398f8d..2649a6b4dc 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSheetFirstOpen.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSheetFirstOpen.test.tsx@@ -5,8 +5,9 @@* @input vitest (jsdom), Testing Library, DropdownMenu, module mocks that* record when the lazily loaded sheet modules are requested and loaded* @output Checks that a bottom-sheet DropdownMenu loads its sheet and rows at- * rest, so the first open renders the actions in the same commit, cold (no- * warm-up)+ * rest. So the first open renders the actions in the same commit, cold (no+ * warm-up). It waits on the dropdown's own requests and on the loads, never+ * on a clock. A cold load can outlast any fixed wait on a loaded machine.* @position Testing for DropdownMenu.tsx and lazyMenuBottomSheet.ts*/@@ -16,20 +17,31 @@ import {DropdownMenu} from './DropdownMenu';import type * as MenuBottomSheetModule from './MenuBottomSheet';import type * as ActionListModule from './MenuBottomSheetActionList';-const modules = vi.hoisted(() => ({- requested: new Set<string>(),- loaded: new Set<string>(),-}));+const modules = vi.hoisted(() => {+ /** A promise the module's own request settles. */+ const signal = () => {+ let fire = () => {};+ const fired = new Promise<void>(resolve => {+ fire = resolve;+ });+ return {fire, fired};+ };+ return {+ loaded: new Set<string>(),+ sheetRequested: signal(),+ rowsRequested: signal(),+ };+});vi.mock('./MenuBottomSheet', async importOriginal => {- modules.requested.add('sheet');+ modules.sheetRequested.fire();const module = await importOriginal<typeof MenuBottomSheetModule>();modules.loaded.add('sheet');return module;});vi.mock('./MenuBottomSheetActionList', async importOriginal => {- modules.requested.add('rows');+ modules.rowsRequested.fire();const module = await importOriginal<typeof ActionListModule>();modules.loaded.add('rows');return module;@@ -54,14 +66,24 @@ it('loads the sheet and its rows at rest, so the first open renders the actionsitems={[{label: 'Edit project'}, {label: 'Archive'}]}/>,);- // Closed, the sheet renders nothing, yet both modules load.+ // Closed, the sheet renders nothing, yet the dropdown requests both modules+ // and both load, however long a cold load takes.expect(document.querySelector('dialog')).toBeNull();- await vi.waitFor(- () => {- expect([...modules.loaded].sort()).toEqual(['rows', 'sheet']);- },- {timeout: 15000},- );+ await act(async () => {+ await Promise.all([+ modules.sheetRequested.fired,+ modules.rowsRequested.fired,+ ]);+ await Promise.all([+ import('./MenuBottomSheet'),+ import('./MenuBottomSheetActionList'),+ ]);+ // A task boundary, not a wait. What the loads let through runs in+ // microtasks: the dropdown keeps the rows' module, and the lazy sheet+ // resolves. They have all run once the next task starts.+ await new Promise(resolve => setTimeout(resolve, 0));+ });+ expect([...modules.loaded].sort()).toEqual(['rows', 'sheet']);// The rows render in the same commit as the opening: nothing suspends.act(() => {@@ -69,4 +91,4 @@ it('loads the sheet and its rows at rest, so the first open renders the actions});expect(screen.getByRole('button', {name: 'Edit project'})).toBeVisible();expect(screen.getByRole('button', {name: 'Archive'})).toBeVisible();-}, 20000);+});diff --git a/packages/core/src/Item/Item.swipeLayer.test.tsx b/packages/core/src/Item/Item.swipeLayer.test.tsxindex 9f1ebc0398..4207e5b557 100644--- a/packages/core/src/Item/Item.swipeLayer.test.tsx+++ b/packages/core/src/Item/Item.swipeLayer.test.tsx@@ -3,20 +3,31 @@/*** @file Item.swipeLayer.test.tsx* @input Item with and without swipe actions; the swipe layer module, spied- * @output Verifies a row without swipe actions never renders the swipe layer,- * and a row with them renders it into the root once it has loaded+ * @output Verifies a row without swipe actions never renders the swipe layer.+ * A row with them renders it into the root once it has loaded, however long+ * the load takes.* @position Companion to Item.test.tsx for the lazily loaded swipe layer*/import {createElement, type ReactNode} from 'react';import {describe, expect, it, vi} from 'vitest';-import {act, render, screen, waitFor} from '@testing-library/react';+import {act, render, screen} from '@testing-library/react';import {Item} from './Item';import type {ItemSwipeLayerProps} from './ItemSwipeLayer';+import {swipeLayerLoaded} from './__tests__/swipeLayerLoaded';-const {layerRenders} = vi.hoisted(() => ({layerRenders: vi.fn()}));+const {layerRenders, layerLoad} = vi.hoisted(() => {+ let release = () => {};+ const held = new Promise<void>(resolve => {+ release = resolve;+ });+ return {layerRenders: vi.fn(), layerLoad: {held, release: () => release()}};+});vi.mock('./ItemSwipeLayer', async importOriginal => {+ // The module loads only when the test releases it. A cold load on a loaded+ // machine is as late, so a wait on a clock would read nothing.+ await layerLoad.held;const actual = await importOriginal<{default: (props: ItemSwipeLayerProps) => ReactNode;}>();@@ -60,11 +71,12 @@ describe('Item and the swipe layer', () => {/>,);const row = screen.getByTestId('row');- const panel = await waitFor(() => {- const found = row.querySelector('[data-swipe-panel="trailing"]');- expect(found).not.toBeNull();- return found;- });+ // The layer's module is still loading: nothing is drawn yet.+ expect(row.querySelector('[data-swipe-panel]')).toBeNull();+ layerLoad.release();+ await swipeLayerLoaded();+ const panel = row.querySelector('[data-swipe-panel="trailing"]');+ expect(panel).not.toBeNull();expect(layerRenders).toHaveBeenCalled();// The layer adds nothing but the panel: the root is still the content// followed by the out-of-flow panel, with no wrapper for either.diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex 729e46bf48..b8993bb481 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -19,15 +19,9 @@ import {expect,vi,} from 'vitest';-import {- act,- cleanup,- fireEvent,- render,- screen,- waitFor,-} from '@testing-library/react';+import {act, cleanup, fireEvent, render, screen} from '@testing-library/react';import {rulesDeclaredFor} from '../__tests__/pressState';+import {swipeLayerLoaded} from './__tests__/swipeLayerLoaded';import userEvent from '@testing-library/user-event';import {LinkProvider} from '../Link/LinkProvider';import {Item} from './Item';@@ -783,7 +777,7 @@ describe('Item', () => {describe('swipeActions', () => {// The panels and the gesture are loaded lazily (React.lazy + Suspense), so- // the first row with swipe actions renders them a tick after it mounts.+ // the first row with swipe actions renders them once that module is in.// Mount one once up front: the resolved module is cached on the lazy// component, and every row below renders its panels synchronously.beforeAll(async () => {@@ -794,11 +788,10 @@ describe('swipeActions', () => {swipeActions={{leading: [{label: 'Unread', onActivate: () => {}}]}}/>,);- await waitFor(() => {- expect(- screen.getByTestId('warm').querySelector('[data-swipe-panel]'),- ).not.toBeNull();- });+ await swipeLayerLoaded();+ expect(+ screen.getByTestId('warm').querySelector('[data-swipe-panel]'),+ ).not.toBeNull();cleanup();});diff --git a/packages/core/src/Item/__tests__/swipeLayerLoaded.ts b/packages/core/src/Item/__tests__/swipeLayerLoaded.tsnew file mode 100644index 0000000000..ecf679d868--- /dev/null+++ b/packages/core/src/Item/__tests__/swipeLayerLoaded.ts@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swipeLayerLoaded.ts+ * @input Item's lazily loaded swipe layer (ItemSwipeLayer.tsx)+ * @output swipeLayerLoaded, which resolves once that layer has loaded and React+ * has rendered it into every row that waits for it+ * @position Test helper for Item's and List's swipe tests+ *+ * On a loaded machine the load can outlast any fixed wait, so a test that+ * polls for a panel on a clock reads nothing. This awaits the module inside+ * `act`. `act` then renders what the load let through.+ */++import {act} from '@testing-library/react';++export async function swipeLayerLoaded(): Promise<void> {+ await act(async () => {+ await import('../ItemSwipeLayer');+ });+}diff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsxindex 8ed1f09f40..ea930d22f6 100644--- a/packages/core/src/List/List.test.tsx+++ b/packages/core/src/List/List.test.tsx@@ -10,9 +10,10 @@*/import {describe, it, expect, vi} from 'vitest';-import {cleanup, render, screen, waitFor} from '@testing-library/react';+import {cleanup, render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {rulesDeclaredFor} from '../__tests__/pressState';+import {swipeLayerLoaded} from '../Item/__tests__/swipeLayerLoaded';import {List} from './List';import {ListItem} from './ListItem';import {ListMarkerScope} from './ListContext';@@ -1041,11 +1042,9 @@ describe('List and swipe actions', () => {expect(row.tagName).toBe('LI');expect(row.parentElement).toBe(screen.getByRole('list'));// The panel arrives with the lazily loaded swipe layer.- const panel = await waitFor(() => {- const found = row.querySelector('[data-swipe-panel="trailing"]');- expect(found).not.toBeNull();- return found;- });+ await swipeLayerLoaded();+ const panel = row.querySelector('[data-swipe-panel="trailing"]');+ expect(panel).not.toBeNull();// Commit: presentational.expect(panel).toHaveAttribute('aria-hidden', 'true');});