Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

settingsLayout.browser.test.tsx

68 lines2.6 KB

1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import { scrollToSettingsTarget } from "./settingsLayout";
4​
5const PULSE = "settings-search-target-pulse";
6​
7afterEach(() => {
8 document.body.replaceChildren();
9 vi.restoreAllMocks();
10});
11​
12function mount(html: string) {
13 document.body.innerHTML = html;
14 return vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
16​
17function reduceMotion(matches: boolean) {
18 vi.spyOn(window, "matchMedia").mockReturnValue({ matches } as MediaQueryList);
20​
21describe("settings search targets", () => {
22 it("scrolls a section's header into view, focuses the section, and pulses until blur", () => {
23 reduceMotion(false);
24 const scrollIntoView = mount(
25 `<section id="providers" tabindex="-1"><h2>Providers</h2><p>Body</p></section>`,
26 );
27 const section = document.getElementById("providers")!;
28​
29 expect(scrollToSettingsTarget("providers")).toBe(true);
30 expect(scrollIntoView).toHaveBeenCalledOnce();
31 expect(scrollIntoView.mock.contexts[0]).toBe(section.querySelector("h2"));
32 expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" });
33 expect(document.activeElement).toBe(section);
34 expect(section.classList.contains(PULSE)).toBe(true);
35​
36 section.blur();
37 expect(section.classList.contains(PULSE)).toBe(false);
38 });
39​
40 it("restarts the pulse when the same destination is chosen again", () => {
41 reduceMotion(false);
42 mount(`<div id="word-wrap" tabindex="-1" class="${PULSE}"></div>`);
43 const target = document.getElementById("word-wrap")!;
44 const observer = new MutationObserver(() => {});
45 observer.observe(target, { attributeFilter: ["class"], attributeOldValue: true });
46​
47 scrollToSettingsTarget("word-wrap");
48 const previousClasses = observer.takeRecords().map((record) => record.oldValue);
49 expect(previousClasses).toEqual([PULSE, ""]);
50 expect(target.classList.contains(PULSE)).toBe(true);
51 });
52​
53 it("does not animate the destination when reduced motion is requested", () => {
54 reduceMotion(true);
55 const scrollIntoView = mount(`<div id="word-wrap" tabindex="-1"></div>`);
56 const target = document.getElementById("word-wrap")!;
57​
58 expect(scrollToSettingsTarget("word-wrap")).toBe(true);
59 expect(scrollIntoView.mock.contexts[0]).toBe(target);
60 expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "auto", block: "center" });
61 expect(document.activeElement).toBe(target);
62 expect(target.classList.contains(PULSE)).toBe(false);
63 });
64​
65 it("leaves not-yet-mounted destinations to their mount lifecycle", () => {
66 expect(scrollToSettingsTarget("archive")).toBe(false);
67 });
68});