import { expect, vi } from "vite-plus/test"; import type { Locator } from "vite-plus/test/browser"; import { userEvent } from "./context.js"; import { EDITOR_SELECTOR } from "./const.js"; /** Fixed pause for animations/debounces the editor relies on. */ export function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } /** Resolves once `selector` is attached to the DOM, returning the element. */ export function waitForSelector( selector: string, options?: { timeout?: number }, ): Promise { return vi.waitFor( () => { const element = document.querySelector(selector); if (!element) { throw new Error(`Selector not found: ${selector}`); } return element; }, { timeout: options?.timeout ?? 5000 }, ); } /** Resolves once `selector` is no longer in the DOM. */ export function waitForSelectorDetached( selector: string, options?: { timeout?: number }, ): Promise { return vi.waitFor( () => { if (document.querySelector(selector)) { throw new Error(`Selector still attached: ${selector}`); } }, { timeout: options?.timeout ?? 5000 }, ); } export async function focusOnEditor() { const editor = await waitForSelector(EDITOR_SELECTOR); await userEvent.click(editor); } export async function waitForSelectorInEditor(selector: string) { await waitForSelector(`${EDITOR_SELECTOR} ${selector}`, { timeout: 1000 }); } export async function waitForTextInEditor(text: string) { await vi.waitFor( () => { const editor = document.querySelector(EDITOR_SELECTOR); if (!editor || !editor.textContent?.includes(text)) { throw new Error(`Text not found in editor: ${text}`); } }, { timeout: 1000 }, ); } // Vite Plus ships the browser matchers' `expect.element` augmentation against // the bare `vitest` module, but its own `expect` is typed from an internal // module, so the augmentation doesn't attach. Type the accessor locally. type ElementMatchers = { toMatchScreenshot( name?: string, options?: { timeout?: number; screenshotOptions?: { mask?: ReadonlyArray; maskColor?: string; scale?: "css" | "device"; }; comparatorOptions?: { threshold?: number; allowedMismatchedPixels?: number; allowedMismatchedPixelRatio?: number; }; }, ): Promise; toBeVisible(): Promise; not: { toBeVisible(): Promise }; }; type ElementExpect = ( element: Element | null, options?: { timeout?: number }, ) => ElementMatchers; export const expectElement = (expect as unknown as { element: ElementExpect }) .element;