import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library";
import { captureArtifact, expectNoDiagnostics } from "./test/diagnostics";
import App from "./App";
import { clearConnection, connection, saveConnection } from "./lib/connection";
import { library } from "./lib/harvest";
import { navidromeFetch, type FakeMediaFile } from "./test/navidrome";
import { stubResizeObserver } from "./test/env";
/**
* The live-page smoke test: mount the whole app against a fake Navidrome and
* demand a quiet diagnostic channel. This is the guard for the class of bugs
* that surface as console noise plus a halted reactive system (untracked
* reads in the component body, writes from an owned scope, onCleanup inside
* onSettled) — see node_modules/solid-js/skills/reactivity-diagnostics.
*
* The album-grid interaction lives in components/LibraryView.test.tsx.
*/
// Navidrome-shaped MediaFile rows: `duration` is seconds, `trackNumber` is the
// track position. Row 0 is deliberately sub-minute and row 12 an hour-long
// live take, to exercise the padded time column at both ends.
const songs: FakeMediaFile[] = Array.from({ length: 25 }, (_, i) => ({
id: `s${i}`,
title: `Track ${i}`,
artist: "Artist",
album: "Album",
albumId: "al-1",
// The native API sends no artwork id; a track reports a picture with
// `hasCoverArt` and is named to getCoverArt by its own id.
hasCoverArt: true,
duration: i === 12 ? 4325 : 7 + i * 137,
trackNumber: i + 1,
// Navidrome reports the container as `suffix` (the extension the scanner filed)
// and the probed stream as `codec`. Row 0 is hi-res FLAC, row 5 a plain mp3, the
// rest carry no format metadata and must render no chips.
...(i === 0
? { suffix: "flac", codec: "flac", bitRate: 1411, bitDepth: 24, sampleRate: 88200 }
: {}),
...(i === 5 ? { suffix: "mp3", codec: "mp3", bitRate: 320, sampleRate: 44100 } : {}),
}));
beforeEach(() => {
localStorage.clear();
clearConnection();
library().reset();
// jsdom ships no ResizeObserver, which lets VirtualList bail out of the
// observe/teardown branch entirely. Stub one so the mounted app exercises it
// (that branch is where the CLEANUP_IN_FORBIDDEN_SCOPE bug lived).
stubResizeObserver();
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
it("boots, harvests, and renders with zero reactive diagnostics", async () => {
vi.stubGlobal("fetch", navidromeFetch(songs));
saveConnection({ host: "https://nav.example.com", username: "admin", password: "wordpass" });
const { artifact } = await captureArtifact(async () => {
render(() => );
// let the auto-harvest kick in and land before we judge the channel
await waitFor(() => expect(library().status()).toBe("ready"), { timeout: 3000 });
// jsdom has no layout, so the virtualizer's measured viewport is 0 and it
// renders only the buffer's worth of rows. Assert the window is live and
// the full index landed, not a DOM row count.
await waitFor(() =>
expect(document.querySelectorAll(".lib-row--track").length).toBeGreaterThan(0),
);
expect(library().songs()).toHaveLength(25);
// column order is duration → title, in the uniform padded hh:mm:ss shape
const first = document.querySelector(".lib-row--track")!;
expect([...first.children].map((c) => c.className)).toEqual([
"lib-num",
"lib-dur",
"lib-cell lib-title",
"lib-quality",
]);
expect(first.querySelector(".lib-dur")!.textContent).toBe("00:00:07");
// every rendered time is the same 8 chars wide — including the hour-long
// take, which is the case that used to overrun the column into the title
const times = [...document.querySelectorAll(".lib-dur")].map((el) => el!.textContent!);
expect(times.length).toBeGreaterThan(1);
for (const t of times) expect(t).toMatch(/^\d{2}:\d{2}:\d{2}$/);
expect(times).toContain("01:12:05");
// the padding is its own span so it can fade, and only the segments that
// carry no information join it — a real hour fades nothing
expect(first.querySelector(".lib-dur-pad")!.textContent).toBe("00:00:");
const longRow = [...document.querySelectorAll(".lib-row--track")].find(
(r) => r.querySelector(".lib-dur")!.textContent === "01:12:05",
)!;
expect(longRow.querySelector(".lib-dur-pad")!.textContent).toBe("");
// format chips: codec first, then bitrate / bit depth / sample rate. The
// hue rides on data-codec and only on the codec chip — measurements stay
// neutral, and it is the normalized id, so a format cannot fork in color.
const chip = (b: Element) =>
`${b.textContent}·${b.className.replace("lib-badge lib-badge--", "")}·${b.getAttribute("data-codec") ?? "neutral"}`;
expect([...first.querySelectorAll(".lib-badge")].map(chip)).toEqual([
"flac·codec·flac",
"1411k·bitrate·neutral",
"24b·depth·neutral",
"88.2hz·rate·neutral",
]);
const mp3Row = [...document.querySelectorAll(".lib-row--track")][5]!;
expect(mp3Row.querySelector(".lib-badge--codec")!.getAttribute("data-codec")).toBe("mp3");
// a track with no format metadata renders no empty pills
const bare = [...document.querySelectorAll(".lib-row--track")][1]!;
expect(bare.querySelectorAll(".lib-badge")).toHaveLength(0);
});
expectNoDiagnostics(artifact);
expect(library().source()).toBe("navidrome");
});
it("shows the login gate with zero reactive diagnostics when disconnected", async () => {
vi.stubGlobal("fetch", navidromeFetch(songs));
const { artifact } = await captureArtifact(async () => {
render(() => );
await waitFor(() => expect(screen.getByLabelText("host")).toBeTruthy());
});
expectNoDiagnostics(artifact);
});
it("goes from login form to indexed library with zero reactive diagnostics", async () => {
vi.stubGlobal("fetch", navidromeFetch(songs));
const { artifact } = await captureArtifact(async () => {
render(() => );
fireEvent.input(screen.getByLabelText("host"), { target: { value: "nav.example.com" } });
fireEvent.input(screen.getByLabelText("username"), { target: { value: "admin" } });
fireEvent.input(screen.getByLabelText("password"), { target: { value: "wordpass" } });
fireEvent.click(screen.getByRole("button", { name: "connect" }));
// the submit pings, persists the connection, and the Show flips to the
// router — which auto-harvests. This transition is where the old
// component-body write crashed the whole reactive system.
await waitFor(() => expect(library().status()).toBe("ready"), { timeout: 3000 });
await waitFor(() => expect(screen.queryByLabelText("host")).toBeNull());
});
expectNoDiagnostics(artifact);
expect(connection()?.host).toBe("https://nav.example.com");
});