Layout and search fix
🏗️ Build and Test JellyTau / Run Tests (push) Failing after 2m4s
🏗️ Build and Test JellyTau / Android Compile Check (push) Has been skipped
Traceability Validation / Check Requirement Traces (push) Successful in 23s
Build & Release / Run Tests (push) Failing after 2m45s
Build & Release / Build Linux (push) Has been skipped
Build & Release / Build Android (push) Has been skipped
Build & Release / Create Release (push) Has been skipped
🏗️ Build and Test JellyTau / Run Tests (push) Failing after 2m4s
🏗️ Build and Test JellyTau / Android Compile Check (push) Has been skipped
Traceability Validation / Check Requirement Traces (push) Successful in 23s
Build & Release / Run Tests (push) Failing after 2m45s
Build & Release / Build Linux (push) Has been skipped
Build & Release / Build Android (push) Has been skipped
Build & Release / Create Release (push) Has been skipped
This commit is contained in:
@@ -1,432 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/svelte";
|
||||
|
||||
/**
|
||||
* Integration tests for async image loading pattern used in components
|
||||
*
|
||||
* Pattern:
|
||||
* - Component has $state<string> imageUrl = ""
|
||||
* - Component has async loadImageUrl() function
|
||||
* - Component uses $effect to call loadImageUrl when dependencies change
|
||||
* - For lists: uses Map<string, string> to cache URLs per item
|
||||
*/
|
||||
|
||||
// Mock repository with getImageUrl
|
||||
const createMockRepository = () => ({
|
||||
getImageUrl: vi.fn(),
|
||||
});
|
||||
|
||||
describe.skip("Async Image Loading Pattern", () => {
|
||||
// Detailed async pattern tests - core functionality verified in repository-client.test.ts
|
||||
let mockRepository: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mockRepository = createMockRepository();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers();
|
||||
});
|
||||
|
||||
describe("Single Image Loading", () => {
|
||||
it("should load image URL asynchronously on component mount", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
// Simulating component with async image loading
|
||||
const imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
||||
|
||||
expect(imageUrl).toBe("https://server.com/image.jpg");
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item123", "Primary");
|
||||
});
|
||||
|
||||
it("should show placeholder while loading", async () => {
|
||||
mockRepository.getImageUrl.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(() => resolve("https://server.com/image.jpg"), 100))
|
||||
);
|
||||
|
||||
vi.useFakeTimers();
|
||||
const promise = mockRepository.getImageUrl("item123", "Primary");
|
||||
|
||||
// Initially no URL
|
||||
expect(promise).toBeInstanceOf(Promise);
|
||||
|
||||
vi.advanceTimersByTime(100);
|
||||
vi.useRealTimers();
|
||||
|
||||
const result = await promise;
|
||||
expect(result).toBe("https://server.com/image.jpg");
|
||||
});
|
||||
|
||||
it("should reload image when item changes", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image1.jpg");
|
||||
|
||||
const url1 = await mockRepository.getImageUrl("item1", "Primary");
|
||||
expect(url1).toBe("https://server.com/image1.jpg");
|
||||
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2.jpg");
|
||||
|
||||
const url2 = await mockRepository.getImageUrl("item2", "Primary");
|
||||
expect(url2).toBe("https://server.com/image2.jpg");
|
||||
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should not reload image if item ID hasn't changed", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
// First load
|
||||
await mockRepository.getImageUrl("item123", "Primary");
|
||||
|
||||
// Would normally use $effect to track changes
|
||||
// If item ID is same, should not reload (handled by component caching)
|
||||
// This test documents the expected behavior
|
||||
});
|
||||
|
||||
it("should handle load errors gracefully", async () => {
|
||||
mockRepository.getImageUrl.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
// Component should catch error and show placeholder
|
||||
try {
|
||||
await mockRepository.getImageUrl("item123", "Primary");
|
||||
} catch (e) {
|
||||
expect(e).toBeInstanceOf(Error);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("List Image Caching (Map-based)", () => {
|
||||
it("should cache URLs using Map<string, string>", () => {
|
||||
// Simulating component state: imageUrls = $state<Map<string, string>>(new Map())
|
||||
const imageUrls = new Map<string, string>();
|
||||
|
||||
// Load first item
|
||||
imageUrls.set("item1", "https://server.com/image1.jpg");
|
||||
expect(imageUrls.has("item1")).toBe(true);
|
||||
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
|
||||
|
||||
// Load second item
|
||||
imageUrls.set("item2", "https://server.com/image2.jpg");
|
||||
expect(imageUrls.size).toBe(2);
|
||||
|
||||
// Check cache hit
|
||||
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
|
||||
});
|
||||
|
||||
it("should load images only once per item", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
const imageUrls = new Map<string, string>();
|
||||
|
||||
// Simulate loading multiple items
|
||||
const items = [
|
||||
{ id: "item1", name: "Album 1" },
|
||||
{ id: "item2", name: "Album 2" },
|
||||
{ id: "item1", name: "Album 1 (again)" }, // Same ID
|
||||
];
|
||||
|
||||
for (const item of items) {
|
||||
if (!imageUrls.has(item.id)) {
|
||||
const url = await mockRepository.getImageUrl(item.id, "Primary");
|
||||
imageUrls.set(item.id, url);
|
||||
}
|
||||
}
|
||||
|
||||
// Should only call once per unique ID
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should update single item without affecting others", async () => {
|
||||
const imageUrls = new Map<string, string>();
|
||||
|
||||
imageUrls.set("item1", "https://server.com/image1.jpg");
|
||||
imageUrls.set("item2", "https://server.com/image2.jpg");
|
||||
imageUrls.set("item3", "https://server.com/image3.jpg");
|
||||
|
||||
// Update item2
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2_updated.jpg");
|
||||
const newUrl = await mockRepository.getImageUrl("item2", "Primary");
|
||||
imageUrls.set("item2", newUrl);
|
||||
|
||||
// Others should remain unchanged
|
||||
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
|
||||
expect(imageUrls.get("item2")).toBe("https://server.com/image2_updated.jpg");
|
||||
expect(imageUrls.get("item3")).toBe("https://server.com/image3.jpg");
|
||||
});
|
||||
|
||||
it("should clear cache when data changes", () => {
|
||||
const imageUrls = new Map<string, string>();
|
||||
|
||||
imageUrls.set("item1", "https://server.com/image1.jpg");
|
||||
imageUrls.set("item2", "https://server.com/image2.jpg");
|
||||
|
||||
// Clear cache
|
||||
imageUrls.clear();
|
||||
|
||||
expect(imageUrls.size).toBe(0);
|
||||
expect(imageUrls.has("item1")).toBe(false);
|
||||
});
|
||||
|
||||
it("should support Map operations efficiently", () => {
|
||||
const imageUrls = new Map<string, string>();
|
||||
|
||||
// Add items
|
||||
for (let i = 0; i < 100; i++) {
|
||||
imageUrls.set(`item${i}`, `https://server.com/image${i}.jpg`);
|
||||
}
|
||||
|
||||
expect(imageUrls.size).toBe(100);
|
||||
|
||||
// Check specific item
|
||||
expect(imageUrls.has("item50")).toBe(true);
|
||||
expect(imageUrls.get("item50")).toBe("https://server.com/image50.jpg");
|
||||
|
||||
// Iterate
|
||||
let count = 0;
|
||||
imageUrls.forEach(() => {
|
||||
count++;
|
||||
});
|
||||
expect(count).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Component Lifecycle ($effect integration)", () => {
|
||||
it("should trigger load on prop change", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
// Simulate $effect tracking prop changes
|
||||
let effectCount = 0;
|
||||
const trackingEffect = vi.fn(() => {
|
||||
effectCount++;
|
||||
return mockRepository.getImageUrl("item123", "Primary");
|
||||
});
|
||||
|
||||
trackingEffect();
|
||||
expect(effectCount).toBe(1);
|
||||
|
||||
trackingEffect();
|
||||
expect(effectCount).toBe(2);
|
||||
});
|
||||
|
||||
it("should skip load if conditions not met", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
// Simulate conditional loading (e.g., if (!imageUrl && primaryImageTag))
|
||||
let imageUrl = "";
|
||||
const primaryImageTag = "";
|
||||
|
||||
if (!imageUrl && primaryImageTag) {
|
||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
||||
}
|
||||
|
||||
expect(mockRepository.getImageUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle dependent state updates", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
// Simulate component state changes triggering effects
|
||||
const state = {
|
||||
item: { id: "item1", primaryImageTag: "tag1" },
|
||||
imageUrl: "",
|
||||
};
|
||||
|
||||
const loadImage = async () => {
|
||||
if (state.item.primaryImageTag) {
|
||||
state.imageUrl = await mockRepository.getImageUrl(state.item.id, "Primary");
|
||||
}
|
||||
};
|
||||
|
||||
await loadImage();
|
||||
expect(state.imageUrl).toBe("https://server.com/image.jpg");
|
||||
|
||||
// Change item
|
||||
state.item = { id: "item2", primaryImageTag: "tag2" };
|
||||
state.imageUrl = "";
|
||||
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2.jpg");
|
||||
await loadImage();
|
||||
expect(state.imageUrl).toBe("https://server.com/image2.jpg");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error Handling in Async Loading", () => {
|
||||
it("should set empty string on error", async () => {
|
||||
mockRepository.getImageUrl.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
let imageUrl = "";
|
||||
|
||||
try {
|
||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
||||
} catch {
|
||||
imageUrl = ""; // Set to empty on error
|
||||
}
|
||||
|
||||
expect(imageUrl).toBe("");
|
||||
});
|
||||
|
||||
it("should allow retry after error", async () => {
|
||||
mockRepository.getImageUrl
|
||||
.mockRejectedValueOnce(new Error("Network error"))
|
||||
.mockResolvedValueOnce("https://server.com/image.jpg");
|
||||
|
||||
let imageUrl = "";
|
||||
|
||||
// First attempt fails
|
||||
try {
|
||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
||||
} catch {
|
||||
imageUrl = "";
|
||||
}
|
||||
|
||||
// Retry succeeds
|
||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
||||
expect(imageUrl).toBe("https://server.com/image.jpg");
|
||||
});
|
||||
|
||||
it("should handle concurrent load requests", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
// Simulate loading multiple images concurrently
|
||||
const imageUrls = new Map<string, string>();
|
||||
const items = [
|
||||
{ id: "item1" },
|
||||
{ id: "item2" },
|
||||
{ id: "item3" },
|
||||
];
|
||||
|
||||
const promises = items.map(item =>
|
||||
mockRepository.getImageUrl(item.id, "Primary")
|
||||
.then((url: string) => imageUrls.set(item.id, url))
|
||||
.catch(() => imageUrls.set(item.id, ""))
|
||||
);
|
||||
|
||||
await Promise.all(promises);
|
||||
|
||||
expect(imageUrls.size).toBe(3);
|
||||
expect(imageUrls.has("item1")).toBe(true);
|
||||
expect(imageUrls.has("item2")).toBe(true);
|
||||
expect(imageUrls.has("item3")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Performance Characteristics", () => {
|
||||
it("should not reload unnecessarily", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
// Simulate $effect with dependency tracking
|
||||
let dependencyValue = "same";
|
||||
let previousDependency = "same";
|
||||
|
||||
const loadImage = async () => {
|
||||
if (dependencyValue !== previousDependency) {
|
||||
previousDependency = dependencyValue;
|
||||
return await mockRepository.getImageUrl("item123", "Primary");
|
||||
}
|
||||
};
|
||||
|
||||
await loadImage();
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
||||
|
||||
// No change in dependency
|
||||
await loadImage();
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Change dependency
|
||||
dependencyValue = "changed";
|
||||
await loadImage();
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should handle large lists efficiently", async () => {
|
||||
const imageUrls = new Map<string, string>();
|
||||
let loadCount = 0;
|
||||
|
||||
mockRepository.getImageUrl.mockImplementation(() => {
|
||||
loadCount++;
|
||||
return Promise.resolve("https://server.com/image.jpg");
|
||||
});
|
||||
|
||||
// Simulate loading 1000 items but caching URLs
|
||||
const items = Array.from({ length: 1000 }, (_, i) => ({ id: `item${i % 10}` }));
|
||||
|
||||
for (const item of items) {
|
||||
if (!imageUrls.has(item.id)) {
|
||||
const url = await mockRepository.getImageUrl(item.id, "Primary");
|
||||
imageUrls.set(item.id, url);
|
||||
}
|
||||
}
|
||||
|
||||
// Should only load 10 unique images
|
||||
expect(loadCount).toBe(10);
|
||||
expect(imageUrls.size).toBe(10);
|
||||
});
|
||||
|
||||
it("should not block rendering during async loading", () => {
|
||||
mockRepository.getImageUrl.mockImplementation(
|
||||
() => new Promise((resolve) =>
|
||||
setTimeout(() => resolve("https://server.com/image.jpg"), 1000)
|
||||
)
|
||||
);
|
||||
|
||||
// Async operation should not block component rendering
|
||||
const renderTiming = {
|
||||
startRender: Date.now(),
|
||||
loadStart: null as number | null,
|
||||
loadComplete: null as number | null,
|
||||
};
|
||||
|
||||
// Render happens immediately
|
||||
renderTiming.startRender = Date.now();
|
||||
|
||||
// Load happens asynchronously
|
||||
mockRepository.getImageUrl("item123", "Primary").then(() => {
|
||||
renderTiming.loadComplete = Date.now();
|
||||
});
|
||||
|
||||
// Render should complete before load finishes
|
||||
expect(Date.now() - renderTiming.startRender).toBeLessThan(1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Backend Integration", () => {
|
||||
it("should call backend with correct parameters", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
||||
|
||||
await mockRepository.getImageUrl("item123", "Primary", {
|
||||
maxWidth: 300,
|
||||
});
|
||||
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
||||
"item123",
|
||||
"Primary",
|
||||
{
|
||||
maxWidth: 300,
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle backend URL correctly", async () => {
|
||||
const backendUrl = "https://server.com/Items/item123/Images/Primary?maxWidth=300&api_key=token";
|
||||
mockRepository.getImageUrl.mockResolvedValue(backendUrl);
|
||||
|
||||
const url = await mockRepository.getImageUrl("item123", "Primary", { maxWidth: 300 });
|
||||
|
||||
expect(url).toBe(backendUrl);
|
||||
// Frontend never constructs URLs directly
|
||||
expect(url).toContain("api_key=");
|
||||
});
|
||||
|
||||
it("should not require URL construction in frontend", async () => {
|
||||
// Frontend receives pre-constructed URL from backend
|
||||
const preConstructedUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
||||
mockRepository.getImageUrl.mockResolvedValue(preConstructedUrl);
|
||||
|
||||
const url = await mockRepository.getImageUrl("item123", "Primary");
|
||||
|
||||
// Frontend just uses the URL
|
||||
expect(url).toContain("https://");
|
||||
expect(url).toContain("item123");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Regression test: media-list search must surface server results.
|
||||
*
|
||||
* `repository_search` is two-phase — `repo.search()` resolves instantly with
|
||||
* cache-only (downloaded) results, and the merged cache+server union arrives
|
||||
* later via a `search-event`. A consumer that ignores that event only ever
|
||||
* shows downloaded content, so search "finds nothing" for un-downloaded media.
|
||||
*
|
||||
* This test models that two-phase backend faithfully and would fail against a
|
||||
* version of GenericMediaListPage that does not subscribe to `search-event`.
|
||||
*
|
||||
* TRACES: UR-008
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/svelte";
|
||||
import GenericMediaListPage from "./GenericMediaListPage.svelte";
|
||||
import type { MediaListConfig } from "./GenericMediaListPage.svelte";
|
||||
|
||||
vi.mock("$app/navigation", () => ({ goto: vi.fn() }));
|
||||
|
||||
vi.mock("$lib/stores/library", () => ({
|
||||
currentLibrary: {
|
||||
subscribe: vi.fn((fn) => {
|
||||
fn({ id: "lib123", name: "Music" });
|
||||
return vi.fn();
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("$lib/stores/auth", () => ({
|
||||
auth: { getRepository: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("$lib/composables/useServerReachabilityReload", () => ({
|
||||
useServerReachabilityReload: vi.fn(() => ({ markLoaded: vi.fn() })),
|
||||
}));
|
||||
|
||||
// Capture the `search-event` handler the component registers so the test can
|
||||
// drive the deferred (server) phase manually.
|
||||
let searchEventHandler: ((event: { payload: unknown }) => void) | null = null;
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
listen: vi.fn(async (name: string, handler: (event: { payload: unknown }) => void) => {
|
||||
if (name === "search-event") searchEventHandler = handler;
|
||||
return () => {};
|
||||
}),
|
||||
}));
|
||||
|
||||
const ALBUM_CONFIG: MediaListConfig = {
|
||||
itemType: "MusicAlbum",
|
||||
title: "Albums",
|
||||
backPath: "/library/music",
|
||||
searchPlaceholder: "Search albums...",
|
||||
sortOptions: [{ key: "SortName", label: "Title" }],
|
||||
defaultSort: "SortName",
|
||||
displayComponent: "grid",
|
||||
};
|
||||
|
||||
describe("GenericMediaListPage — two-phase search", () => {
|
||||
beforeEach(() => {
|
||||
searchEventHandler = null;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders server results that arrive after the cache-only phase", async () => {
|
||||
// Phase 1 (synchronous) returns cache-only — empty, as it is for a user who
|
||||
// has downloaded nothing. This is the exact condition that used to show
|
||||
// "nothing found" even though the server has matching albums.
|
||||
let capturedRequestId: number | undefined;
|
||||
const search = vi.fn(async (_q: string, _opts: unknown, requestId: number) => {
|
||||
capturedRequestId = requestId;
|
||||
return { items: [], totalRecordCount: 0 };
|
||||
});
|
||||
|
||||
const getItems = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||
getItems,
|
||||
search,
|
||||
} as any);
|
||||
|
||||
const { container } = render(GenericMediaListPage, { props: { config: ALBUM_CONFIG } });
|
||||
|
||||
// Let the initial (mount) load finish so the debounced search effect is armed.
|
||||
await waitFor(() => expect(getItems).toHaveBeenCalled());
|
||||
|
||||
const input = container.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.input(input, { target: { value: "Rumours" } });
|
||||
|
||||
// Debounced search fires after 300ms and returns the empty cache result.
|
||||
// The `search-event` listener is registered lazily as part of searching.
|
||||
await waitFor(() => expect(search).toHaveBeenCalled());
|
||||
await waitFor(() => expect(searchEventHandler).not.toBeNull());
|
||||
// Cache-only phase: nothing to show yet (the results counter reads zero).
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText(/0 musicalbums matching/)).toBeTruthy()
|
||||
);
|
||||
|
||||
// Phase 2: backend emits the merged cache+server union for this request.
|
||||
expect(capturedRequestId).toBeTypeOf("number");
|
||||
searchEventHandler!({
|
||||
payload: {
|
||||
requestId: capturedRequestId,
|
||||
result: {
|
||||
items: [{ id: "album1", name: "Rumours", type: "MusicAlbum" }],
|
||||
totalRecordCount: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// The server result must now be reflected in the list. Old code (no
|
||||
// listener) never reached this state — the count stayed at zero.
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText(/1 musicalbum matching/)).toBeTruthy()
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores a search-event whose requestId is stale", async () => {
|
||||
const search = vi.fn(async () => ({ items: [], totalRecordCount: 0 }));
|
||||
const getItems = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||
getItems,
|
||||
search,
|
||||
} as any);
|
||||
|
||||
const { container } = render(GenericMediaListPage, { props: { config: ALBUM_CONFIG } });
|
||||
await waitFor(() => expect(getItems).toHaveBeenCalled());
|
||||
|
||||
const input = container.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.input(input, { target: { value: "Rumours" } });
|
||||
await waitFor(() => expect(search).toHaveBeenCalled());
|
||||
await waitFor(() => expect(searchEventHandler).not.toBeNull());
|
||||
|
||||
// A superseded query's late result (wrong requestId) must not render.
|
||||
searchEventHandler!({
|
||||
payload: {
|
||||
requestId: -999,
|
||||
result: {
|
||||
items: [{ id: "stale", name: "Stale Album", type: "MusicAlbum" }],
|
||||
totalRecordCount: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await new Promise((r) => setTimeout(r, 0));
|
||||
expect(screen.queryByText("Stale Album")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
<!-- TRACES: UR-007, UR-029, UR-030 | DR-007, DR-032, DR-033 -->
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { goto } from "$app/navigation";
|
||||
import { navigateBack } from "$lib/utils/navigation";
|
||||
import { currentLibrary } from "$lib/stores/library";
|
||||
@@ -13,7 +14,7 @@
|
||||
import BackButton from "$lib/components/common/BackButton.svelte";
|
||||
import ResultsCounter from "$lib/components/common/ResultsCounter.svelte";
|
||||
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
||||
import type { MediaItem, Library, ItemType } from "$lib/api/types";
|
||||
import type { MediaItem, Library, ItemType, SearchResult } from "$lib/api/types";
|
||||
import LibraryGrid from "./LibraryGrid.svelte";
|
||||
import TrackList from "./TrackList.svelte";
|
||||
import AlphabetScrollBar from "./AlphabetScrollBar.svelte";
|
||||
@@ -54,6 +55,31 @@
|
||||
let searchTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let initialLoadDone = false;
|
||||
|
||||
/**
|
||||
* Payload of the backend `search-event` (mirrors Rust `SearchUpdateEvent`).
|
||||
* `repo.search()` resolves instantly with cache-only (downloaded) results;
|
||||
* the merged cache+server union arrives later via this event.
|
||||
*/
|
||||
interface SearchUpdateEvent {
|
||||
requestId: number;
|
||||
result: SearchResult;
|
||||
}
|
||||
|
||||
// Monotonic id identifying the latest search request. The deferred
|
||||
// `search-event` is only applied when its requestId still matches, so
|
||||
// out-of-order / superseded server results never clobber fresher ones.
|
||||
let searchRequestId = 0;
|
||||
let unlistenSearch: UnlistenFn | null = null;
|
||||
|
||||
async function ensureSearchListener() {
|
||||
if (unlistenSearch) return;
|
||||
unlistenSearch = await listen<SearchUpdateEvent>("search-event", (event) => {
|
||||
const { requestId, result } = event.payload;
|
||||
if (requestId !== searchRequestId) return;
|
||||
items = excludePodcasts(result.items);
|
||||
});
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
sortBy = config.defaultSort;
|
||||
});
|
||||
@@ -82,12 +108,26 @@
|
||||
// Use backend search if search query is provided, otherwise use getItems with sort
|
||||
// HACK: excludePodcasts drops the "Podcasts" folder stored in the music library.
|
||||
if (debouncedSearchQuery.trim()) {
|
||||
const result = await repo.search(debouncedSearchQuery, {
|
||||
includeItemTypes: [config.itemType],
|
||||
limit: 10000,
|
||||
});
|
||||
items = excludePodcasts(result.items);
|
||||
// Phase 1: instant cache-only (downloaded) results. The merged
|
||||
// cache+server union arrives later via the `search-event` listener,
|
||||
// tagged with this requestId so superseded queries are ignored.
|
||||
await ensureSearchListener();
|
||||
const requestId = ++searchRequestId;
|
||||
const result = await repo.search(
|
||||
debouncedSearchQuery,
|
||||
{
|
||||
includeItemTypes: [config.itemType],
|
||||
limit: 10000,
|
||||
},
|
||||
requestId
|
||||
);
|
||||
// Only apply if this is still the active query.
|
||||
if (requestId === searchRequestId) {
|
||||
items = excludePodcasts(result.items);
|
||||
}
|
||||
} else {
|
||||
// Leaving search — invalidate any in-flight server results.
|
||||
searchRequestId++;
|
||||
const result = await repo.getItems($currentLibrary.id, {
|
||||
includeItemTypes: [config.itemType],
|
||||
sortBy,
|
||||
@@ -120,6 +160,11 @@
|
||||
}, 300);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (unlistenSearch) unlistenSearch();
|
||||
if (searchTimeout) clearTimeout(searchTimeout);
|
||||
});
|
||||
|
||||
function handleSort(newSort: string) {
|
||||
sortBy = newSort;
|
||||
loadItems();
|
||||
|
||||
@@ -32,7 +32,12 @@ vi.mock("$lib/composables/useServerReachabilityReload", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
describe.skip("GenericMediaListPage", () => {
|
||||
// The component lazily subscribes to the backend `search-event` when searching.
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
listen: vi.fn(async () => () => {}),
|
||||
}));
|
||||
|
||||
describe("GenericMediaListPage", () => {
|
||||
// Component integration tests - core sorting/search/debouncing logic tested in backend-integration.test.ts
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@@ -66,6 +71,16 @@ describe.skip("GenericMediaListPage", () => {
|
||||
});
|
||||
|
||||
it("should load items on mount", async () => {
|
||||
const mockGetItemsFn = vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
totalRecordCount: 0,
|
||||
});
|
||||
|
||||
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||
getItems: mockGetItemsFn,
|
||||
search: vi.fn(),
|
||||
} as any);
|
||||
|
||||
const config = {
|
||||
itemType: "Audio" as const,
|
||||
title: "Tracks",
|
||||
@@ -80,9 +95,7 @@ describe.skip("GenericMediaListPage", () => {
|
||||
props: { config },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
// loadItems should have been called
|
||||
});
|
||||
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalledWith("lib123", expect.anything()));
|
||||
});
|
||||
|
||||
it("should display sort options", () => {
|
||||
@@ -111,8 +124,14 @@ describe.skip("GenericMediaListPage", () => {
|
||||
});
|
||||
|
||||
describe("Search Functionality", () => {
|
||||
it("should debounce search input for 300ms", async () => {
|
||||
vi.useFakeTimers();
|
||||
it("should debounce rapid keystrokes into a single search for the final value", async () => {
|
||||
const mockSearchFn = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||
const mockGetItemsFn = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||
|
||||
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||
getItems: mockGetItemsFn,
|
||||
search: mockSearchFn,
|
||||
} as any);
|
||||
|
||||
const config = {
|
||||
itemType: "Audio" as const,
|
||||
@@ -128,29 +147,33 @@ describe.skip("GenericMediaListPage", () => {
|
||||
props: { config },
|
||||
});
|
||||
|
||||
// Let the mount load settle so the debounce effect is armed.
|
||||
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
|
||||
|
||||
// Drive the debounce window deterministically with fake timers, flushing
|
||||
// the async loadItems() microtasks after the timer fires.
|
||||
vi.useFakeTimers();
|
||||
const searchInput = container.querySelector("input") as HTMLInputElement;
|
||||
|
||||
// Type into search
|
||||
fireEvent.input(searchInput, { target: { value: "t" } });
|
||||
expect(searchInput.value).toBe("t");
|
||||
|
||||
// Search should not trigger immediately
|
||||
vi.advanceTimersByTime(100);
|
||||
|
||||
// Add more characters
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
fireEvent.input(searchInput, { target: { value: "te" } });
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
fireEvent.input(searchInput, { target: { value: "tes" } });
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
fireEvent.input(searchInput, { target: { value: "test" } });
|
||||
|
||||
// Still shouldn't trigger (only 100ms passed total)
|
||||
vi.advanceTimersByTime(100);
|
||||
|
||||
// Now advance to 300ms total - search should trigger
|
||||
vi.advanceTimersByTime(100);
|
||||
|
||||
await waitFor(() => {
|
||||
// Search should have been debounced
|
||||
});
|
||||
// 200ms after the final keystroke: still inside the 300ms window, so no
|
||||
// search has fired despite four keystrokes.
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(mockSearchFn).not.toHaveBeenCalled();
|
||||
|
||||
// Cross the threshold: exactly one search, for the final value.
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
vi.useRealTimers();
|
||||
|
||||
expect(mockSearchFn).toHaveBeenCalledTimes(1);
|
||||
expect(mockSearchFn).toHaveBeenCalledWith("test", expect.anything(), expect.any(Number));
|
||||
});
|
||||
|
||||
it("should use backend search when search query is provided", async () => {
|
||||
@@ -159,8 +182,13 @@ describe.skip("GenericMediaListPage", () => {
|
||||
totalRecordCount: 1,
|
||||
});
|
||||
|
||||
const mockGetItemsFn = vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
totalRecordCount: 0,
|
||||
});
|
||||
|
||||
const mockRepository = {
|
||||
getItems: vi.fn(),
|
||||
getItems: mockGetItemsFn,
|
||||
search: mockSearchFn,
|
||||
};
|
||||
|
||||
@@ -178,25 +206,27 @@ describe.skip("GenericMediaListPage", () => {
|
||||
displayComponent: "tracklist" as const,
|
||||
};
|
||||
|
||||
vi.useFakeTimers();
|
||||
const { container } = render(GenericMediaListPage, {
|
||||
props: { config },
|
||||
});
|
||||
|
||||
// Wait for the initial mount load so the debounced search effect is armed.
|
||||
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
|
||||
|
||||
const searchInput = container.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.input(searchInput, { target: { value: "test" } });
|
||||
|
||||
// Advance timer to trigger debounced search
|
||||
vi.advanceTimersByTime(300);
|
||||
|
||||
// search() is called as search(query, options, requestId).
|
||||
await waitFor(() => {
|
||||
expect(mockSearchFn).toHaveBeenCalledWith("test", expect.objectContaining({
|
||||
includeItemTypes: ["Audio"],
|
||||
limit: 10000,
|
||||
}));
|
||||
expect(mockSearchFn).toHaveBeenCalledWith(
|
||||
"test",
|
||||
expect.objectContaining({
|
||||
includeItemTypes: ["Audio"],
|
||||
limit: 10000,
|
||||
}),
|
||||
expect.any(Number)
|
||||
);
|
||||
});
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("should use getItems without search for empty query", async () => {
|
||||
@@ -416,15 +446,18 @@ describe.skip("GenericMediaListPage", () => {
|
||||
});
|
||||
|
||||
it("should include correct itemType in search request", async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
const mockSearchFn = vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
totalRecordCount: 0,
|
||||
});
|
||||
|
||||
const mockGetItemsFn = vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
totalRecordCount: 0,
|
||||
});
|
||||
|
||||
const mockRepository = {
|
||||
getItems: vi.fn(),
|
||||
getItems: mockGetItemsFn,
|
||||
search: mockSearchFn,
|
||||
};
|
||||
|
||||
@@ -446,17 +479,20 @@ describe.skip("GenericMediaListPage", () => {
|
||||
props: { config },
|
||||
});
|
||||
|
||||
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
|
||||
|
||||
const searchInput = container.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.input(searchInput, { target: { value: "album" } });
|
||||
vi.advanceTimersByTime(300);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSearchFn).toHaveBeenCalledWith("album", expect.objectContaining({
|
||||
includeItemTypes: ["MusicAlbum"],
|
||||
}));
|
||||
expect(mockSearchFn).toHaveBeenCalledWith(
|
||||
"album",
|
||||
expect.objectContaining({
|
||||
includeItemTypes: ["MusicAlbum"],
|
||||
}),
|
||||
expect.any(Number)
|
||||
);
|
||||
});
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -536,6 +572,7 @@ describe.skip("GenericMediaListPage", () => {
|
||||
|
||||
it("should handle missing library gracefully", async () => {
|
||||
const { goto } = await import("$app/navigation");
|
||||
vi.mocked(goto).mockClear();
|
||||
|
||||
const mockGetItemsFn = vi.fn();
|
||||
|
||||
@@ -548,14 +585,12 @@ describe.skip("GenericMediaListPage", () => {
|
||||
mockRepository as any
|
||||
);
|
||||
|
||||
// Mock currentLibrary to return null
|
||||
vi.resetModules();
|
||||
vi.mocked((await import("$lib/stores/library")).currentLibrary.subscribe).mockImplementation(
|
||||
(fn: any) => {
|
||||
fn(null);
|
||||
return vi.fn();
|
||||
}
|
||||
);
|
||||
// Deliver a null current library for this test only.
|
||||
const currentLibrary = vi.mocked((await import("$lib/stores/library")).currentLibrary);
|
||||
currentLibrary.subscribe.mockImplementation((fn: any) => {
|
||||
fn(null);
|
||||
return vi.fn();
|
||||
});
|
||||
|
||||
const config = {
|
||||
itemType: "Audio" as const,
|
||||
@@ -571,9 +606,15 @@ describe.skip("GenericMediaListPage", () => {
|
||||
props: { config },
|
||||
});
|
||||
|
||||
// Should navigate to back path when library is missing
|
||||
await waitFor(() => {
|
||||
// goto would be called with config.backPath
|
||||
// With no current library, loadItems bails out to the back path and never
|
||||
// queries the repository.
|
||||
await waitFor(() => expect(goto).toHaveBeenCalledWith("/library/music"));
|
||||
expect(mockGetItemsFn).not.toHaveBeenCalled();
|
||||
|
||||
// Restore the default (non-null) library for subsequent tests.
|
||||
currentLibrary.subscribe.mockImplementation((fn: any) => {
|
||||
fn({ id: "lib123", name: "Music" });
|
||||
return vi.fn();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,373 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/svelte";
|
||||
import MediaCard from "./MediaCard.svelte";
|
||||
|
||||
vi.mock("$lib/stores/auth", () => ({
|
||||
auth: {
|
||||
getRepository: vi.fn(() => ({
|
||||
getImageUrl: vi.fn(),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
describe.skip("MediaCard - Async Image Loading", () => {
|
||||
// Component rendering tests skipped - core async logic tested in repository-client.test.ts
|
||||
let mockRepository: any;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockRepository = {
|
||||
getImageUrl: vi.fn(),
|
||||
};
|
||||
|
||||
vi.mocked((global as any).__stores_auth?.auth?.getRepository).mockReturnValue(mockRepository);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers();
|
||||
});
|
||||
|
||||
describe("Image Loading", () => {
|
||||
it("should load image URL asynchronously", async () => {
|
||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
||||
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "abc123",
|
||||
};
|
||||
|
||||
const { container } = render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
// Component should render immediately with placeholder
|
||||
expect(container).toBeTruthy();
|
||||
|
||||
// Wait for image URL to load
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
||||
"item123",
|
||||
"Primary",
|
||||
expect.objectContaining({
|
||||
maxWidth: 300,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should show placeholder while image is loading", async () => {
|
||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
||||
mockRepository.getImageUrl.mockImplementation(
|
||||
() => new Promise((resolve) => setTimeout(() => resolve(mockImageUrl), 100))
|
||||
);
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "abc123",
|
||||
};
|
||||
|
||||
const { container } = render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
// Placeholder should be visible initially
|
||||
const placeholder = container.querySelector(".placeholder");
|
||||
if (placeholder) {
|
||||
expect(placeholder).toBeTruthy();
|
||||
}
|
||||
|
||||
// Wait for image to load
|
||||
vi.useFakeTimers();
|
||||
vi.advanceTimersByTime(100);
|
||||
vi.useRealTimers();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("should update image URL when item changes", async () => {
|
||||
const mockImageUrl1 = "https://server.com/Items/item1/Images/Primary?api_key=token";
|
||||
const mockImageUrl2 = "https://server.com/Items/item2/Images/Primary?api_key=token";
|
||||
|
||||
mockRepository.getImageUrl.mockResolvedValueOnce(mockImageUrl1);
|
||||
|
||||
const mediaItem1 = {
|
||||
id: "item1",
|
||||
name: "Album 1",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "tag1",
|
||||
};
|
||||
|
||||
const { rerender } = render(MediaCard, {
|
||||
props: { item: mediaItem1 },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item1", "Primary", expect.any(Object));
|
||||
});
|
||||
|
||||
// Change item
|
||||
mockRepository.getImageUrl.mockResolvedValueOnce(mockImageUrl2);
|
||||
|
||||
const mediaItem2 = {
|
||||
id: "item2",
|
||||
name: "Album 2",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "tag2",
|
||||
};
|
||||
|
||||
await rerender({ item: mediaItem2 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item2", "Primary", expect.any(Object));
|
||||
});
|
||||
});
|
||||
|
||||
it("should not reload image if item ID hasn't changed", async () => {
|
||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
||||
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "abc123",
|
||||
};
|
||||
|
||||
const { rerender } = render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Rerender with same item
|
||||
await rerender({ item: mediaItem });
|
||||
|
||||
// Should not call getImageUrl again
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should handle missing primary image tag gracefully", async () => {
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
// primaryImageTag is undefined
|
||||
};
|
||||
|
||||
const { container } = render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
// Should render without calling getImageUrl
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Should show placeholder
|
||||
expect(container).toBeTruthy();
|
||||
});
|
||||
|
||||
it("should handle image load errors gracefully", async () => {
|
||||
mockRepository.getImageUrl.mockRejectedValue(new Error("Failed to load image"));
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "abc123",
|
||||
};
|
||||
|
||||
const { container } = render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Should still render without crashing
|
||||
expect(container).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Image Options", () => {
|
||||
it("should pass correct options to getImageUrl", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "abc123",
|
||||
};
|
||||
|
||||
render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
||||
"item123",
|
||||
"Primary",
|
||||
{
|
||||
maxWidth: 300,
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should include tag in image options when available", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "tag123",
|
||||
};
|
||||
|
||||
render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
||||
"item123",
|
||||
"Primary",
|
||||
{
|
||||
maxWidth: 300,
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Caching", () => {
|
||||
it("should cache image URLs to avoid duplicate requests", async () => {
|
||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
||||
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "abc123",
|
||||
};
|
||||
|
||||
// Render same item multiple times
|
||||
const { rerender } = render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Rerender with same item
|
||||
await rerender({ item: mediaItem });
|
||||
|
||||
// Should still only have called once (cached)
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should have separate cache entries for different items", async () => {
|
||||
const mockImageUrl1 = "https://server.com/Items/item1/Images/Primary?api_key=token";
|
||||
const mockImageUrl2 = "https://server.com/Items/item2/Images/Primary?api_key=token";
|
||||
|
||||
let callCount = 0;
|
||||
mockRepository.getImageUrl.mockImplementation(() => {
|
||||
callCount++;
|
||||
return Promise.resolve(callCount === 1 ? mockImageUrl1 : mockImageUrl2);
|
||||
});
|
||||
|
||||
const item1 = {
|
||||
id: "item1",
|
||||
name: "Album 1",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "tag1",
|
||||
};
|
||||
|
||||
const item2 = {
|
||||
id: "item2",
|
||||
name: "Album 2",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "tag2",
|
||||
};
|
||||
|
||||
const { rerender } = render(MediaCard, {
|
||||
props: { item: item1 },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
await rerender({ item: item2 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// Change back to item 1 - should use cached value
|
||||
await rerender({ item: item1 });
|
||||
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Reactive Updates", () => {
|
||||
it("should respond to property changes via $effect", async () => {
|
||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
|
||||
|
||||
const mediaItem = {
|
||||
id: "item123",
|
||||
name: "Test Album",
|
||||
type: "MusicAlbum" as const,
|
||||
serverId: "server-1",
|
||||
primaryImageTag: "abc123",
|
||||
};
|
||||
|
||||
const { rerender } = render(MediaCard, {
|
||||
props: { item: mediaItem },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRepository.getImageUrl).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const previousCallCount = mockRepository.getImageUrl.mock.calls.length;
|
||||
|
||||
// Update a property that shouldn't trigger reload
|
||||
await rerender({
|
||||
item: {
|
||||
...mediaItem,
|
||||
name: "Updated Album Name",
|
||||
},
|
||||
});
|
||||
|
||||
// Should not call getImageUrl again (same primaryImageTag)
|
||||
expect(mockRepository.getImageUrl.mock.calls.length).toBe(previousCallCount);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -54,8 +54,9 @@ import { invoke } from "@tauri-apps/api/core";
|
||||
import TrackList from "./TrackList.svelte";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { toast } from "$lib/stores/toast";
|
||||
|
||||
describe.skip("TrackList", () => {
|
||||
describe("TrackList", () => {
|
||||
const mockRepository = {
|
||||
getAudioStreamUrl: vi.fn(),
|
||||
getImageUrl: vi.fn(),
|
||||
@@ -118,7 +119,8 @@ describe.skip("TrackList", () => {
|
||||
|
||||
expect(getAllByText("Song 1").length).toBeGreaterThan(0);
|
||||
expect(getAllByText("Song 2").length).toBeGreaterThan(0);
|
||||
expect(getAllByText(/Song 3 with a Very Long Name/).length).toBeGreaterThan(0);
|
||||
// Long names are abbreviated in the middle via truncateMiddle(name, 48).
|
||||
expect(getAllByText(/Song 3 with a Very Long .*Should Be Truncated/).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("shows loading skeleton when loading=true", () => {
|
||||
@@ -137,10 +139,12 @@ describe.skip("TrackList", () => {
|
||||
});
|
||||
|
||||
it("shows artist column by default", () => {
|
||||
const { getByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
const { getByText, getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
|
||||
// Header only exists in the desktop table.
|
||||
expect(getByText("Artist")).toBeTruthy();
|
||||
expect(getByText("Artist 1")).toBeTruthy();
|
||||
// Artist name renders in both desktop and mobile views.
|
||||
expect(getAllByText("Artist 1").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("hides artist column when showArtist=false", () => {
|
||||
@@ -153,10 +157,12 @@ describe.skip("TrackList", () => {
|
||||
});
|
||||
|
||||
it("shows album column by default", () => {
|
||||
const { getByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
const { getByText, getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
|
||||
// Header only exists in the desktop table.
|
||||
expect(getByText("Album")).toBeTruthy();
|
||||
expect(getByText("Album 1")).toBeTruthy();
|
||||
// Album name renders in both desktop and mobile views.
|
||||
expect(getAllByText("Album 1").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("hides album column when showAlbum=false", () => {
|
||||
@@ -185,12 +191,13 @@ describe.skip("TrackList", () => {
|
||||
},
|
||||
];
|
||||
|
||||
// Component renders both desktop and mobile views
|
||||
// formatDuration(undefined) renders an empty string, so the row still
|
||||
// renders without crashing and the track title is present.
|
||||
const { getAllByText } = render(TrackList, {
|
||||
props: { tracks: tracksWithoutDuration },
|
||||
});
|
||||
|
||||
expect(getAllByText("-").length).toBeGreaterThan(0);
|
||||
expect(getAllByText("Song 1").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("handles tracks without artist", () => {
|
||||
@@ -198,20 +205,24 @@ describe.skip("TrackList", () => {
|
||||
{
|
||||
...mockTracks[0],
|
||||
artists: undefined,
|
||||
artistItems: undefined,
|
||||
},
|
||||
];
|
||||
|
||||
const { getByText } = render(TrackList, {
|
||||
// The artist fallback renders "-" in both desktop and mobile views.
|
||||
const { getAllByText } = render(TrackList, {
|
||||
props: { tracks: tracksWithoutArtist },
|
||||
});
|
||||
|
||||
expect(getByText("-")).toBeTruthy();
|
||||
expect(getAllByText("-").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders multiple artists joined with comma", () => {
|
||||
const { getByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
// Tracks fall back to artists.join(", ") when artistItems is absent;
|
||||
// the joined string renders in both desktop and mobile views.
|
||||
const { getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
|
||||
expect(getByText("Artist 3, Artist 4")).toBeTruthy();
|
||||
expect(getAllByText("Artist 3, Artist 4").length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -278,25 +289,8 @@ describe.skip("TrackList", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.skip("calls getAudioStreamUrl for each track", async () => {
|
||||
// NOTE: This test is skipped because the code was refactored to use player_play_tracks
|
||||
// which sends trackIds to the backend. The backend now handles all metadata/stream fetching.
|
||||
// This test expected the old behavior where frontend called getAudioStreamUrl.
|
||||
});
|
||||
|
||||
it.skip("includes artwork URLs in queue items", async () => {
|
||||
// NOTE: This test is skipped because the code was refactored.
|
||||
// Stream URLs and artwork URLs are no longer fetched by frontend.
|
||||
// Backend handles all metadata and stream URL fetching via player_play_tracks.
|
||||
});
|
||||
|
||||
it.skip("handles tracks without artwork gracefully", async () => {
|
||||
// NOTE: This test is skipped because the code no longer includes artwork URLs
|
||||
// in queue items sent to backend. Backend handles artwork fetching independently.
|
||||
});
|
||||
|
||||
it("shows error alert when playback fails", async () => {
|
||||
const alertSpy = vi.spyOn(window, "alert").mockImplementation(() => {});
|
||||
it("shows error toast when playback fails", async () => {
|
||||
const toastSpy = vi.spyOn(toast, "error").mockImplementation(() => "");
|
||||
(invoke as any).mockRejectedValue(new Error("Network error"));
|
||||
|
||||
const { container } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
@@ -309,16 +303,19 @@ describe.skip("TrackList", () => {
|
||||
await fireEvent.click(firstTrackButton!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to play track")
|
||||
expect(toastSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to play track"),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
alertSpy.mockRestore();
|
||||
toastSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("handles auth errors gracefully", async () => {
|
||||
const alertSpy = vi.spyOn(window, "alert").mockImplementation(() => {});
|
||||
const toastSpy = vi.spyOn(toast, "error").mockImplementation(() => "");
|
||||
// No repository → requireHandle() throws "No repository available",
|
||||
// which the default handler surfaces via toast.error.
|
||||
(auth.getRepository as any).mockReturnValue(null as any);
|
||||
|
||||
const { container } = render(TrackList, { props: { tracks: mockTracks } });
|
||||
@@ -331,22 +328,18 @@ describe.skip("TrackList", () => {
|
||||
await fireEvent.click(firstTrackButton!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Not authenticated")
|
||||
expect(toastSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to play track"),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
alertSpy.mockRestore();
|
||||
toastSpy.mockRestore();
|
||||
|
||||
// Restore mock for other tests
|
||||
(auth.getRepository as any).mockReturnValue(mockRepository as any);
|
||||
});
|
||||
|
||||
it.skip("handles stream URL generation errors", async () => {
|
||||
// NOTE: This test is skipped because stream URLs are no longer fetched by frontend.
|
||||
// The code now uses player_play_tracks which sends trackIds to backend.
|
||||
// Backend handles all stream URL generation, so this error path no longer exists.
|
||||
});
|
||||
});
|
||||
|
||||
describe("Custom Callback Tests", () => {
|
||||
|
||||
Reference in New Issue
Block a user