diff --git a/tests/accessible-table.dom.test.tsx b/tests/accessible-table.dom.test.tsx index f3aef2a94..e39ffc369 100644 --- a/tests/accessible-table.dom.test.tsx +++ b/tests/accessible-table.dom.test.tsx @@ -1,30 +1,14 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import { AccessibleTable } from "@/components/AccessibleTable"; +import { installMatchMediaStub as setMatchMedia } from "./setup/jsdom.setup"; // Interactive counterpart to tests/accessible-table-fallback.test.ts (which asserts // on the SSR-rendered HTML string). This exercises the same component under jsdom // via @testing-library/react so real DOM state + user interaction are covered: the // mobile "Expand table" affordance and the full-screen dialog it toggles. -function setMatchMedia(matches: boolean) { - Object.defineProperty(window, "matchMedia", { - writable: true, - configurable: true, - value: vi.fn().mockImplementation((query: string) => ({ - matches, - media: query, - onchange: null, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - addListener: vi.fn(), - removeListener: vi.fn(), - dispatchEvent: vi.fn(), - })), - }); -} - const columns = ["Score", "Management"]; const rows = [["0", "Monitor observations"]]; diff --git a/tests/setup/jsdom.setup.ts b/tests/setup/jsdom.setup.ts index 0f945f56b..7a0f3209e 100644 --- a/tests/setup/jsdom.setup.ts +++ b/tests/setup/jsdom.setup.ts @@ -9,7 +9,7 @@ import "@testing-library/jest-dom/vitest"; import { cleanup } from "@testing-library/react"; import { afterEach, beforeEach, vi } from "vitest"; -function installMatchMediaStub(matches = false) { +export function installMatchMediaStub(matches = false) { Object.defineProperty(window, "matchMedia", { writable: true, configurable: true, @@ -29,9 +29,13 @@ function installMatchMediaStub(matches = false) { beforeEach(() => { installMatchMediaStub(false); // jsdom does not implement scrollIntoView; components call it on focus/expand. - if (!Element.prototype.scrollIntoView) { - Element.prototype.scrollIntoView = vi.fn(); + // Ensure a base impl exists, then re-spy each test so the mock's call history is + // reset every time — vi.restoreAllMocks() only restores vi.spyOn spies, not a + // one-time plain vi.fn() assignment. + if (typeof Element.prototype.scrollIntoView !== "function") { + Element.prototype.scrollIntoView = () => {}; } + vi.spyOn(Element.prototype, "scrollIntoView").mockImplementation(() => {}); }); afterEach(() => {