// @vitest-environment jsdom
import '@testing-library/jest-dom/vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { HttpResponse, http } from 'msw';
import { setupServer } from 'msw/node';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
import { MediaPage } from '../../apps/dashboard/src/features/media/media-page.js';
const now = Date.now();
const mediaItems = [
{
id: 'one', chatUsername: 'alice', chatRoomId: 'room-a', sender: 'alice',
timestamp: now - 60_000, originalUrl: 'https://media.example/one.jpg', fileName: 'one.jpg',
relativePath: 'one.jpg', createdAt: now - 50_000, urlPath: '/media/one.jpg',
owner: { accountId: '@t2_bot:reddit.com', redditUsername: 'bot-account' },
},
{
id: 'two', chatUsername: 'bob', chatRoomId: 'room-b', sender: 'charlie',
timestamp: now - (3 * 86_400_000), originalUrl: 'https://media.example/two.gif', fileName: 'two.gif',
relativePath: 'two.gif', createdAt: now - (3 * 86_400_000), urlPath: '/media/two.gif',
},
{
id: 'three', chatUsername: null, chatRoomId: 'room-c', sender: 'dave',
timestamp: now - (40 * 86_400_000), originalUrl: 'https://media.example/three.png', fileName: 'three.png',
relativePath: 'three.png', createdAt: now - (40 * 86_400_000), urlPath: '/media/three.png',
},
];
function altName(kind: 'Image' | 'GIF', sender: string, timestamp: number): string {
const date = new Intl.DateTimeFormat(undefined, { day: 'numeric', month: 'short' }).format(timestamp);
return `${kind} from u/${sender}, ${date}`;
}
const aliceAlt = altName('Image', 'alice', mediaItems[0].timestamp);
const charlieAlt = altName('GIF', 'charlie', mediaItems[1].timestamp);
const daveAlt = altName('Image', 'dave', mediaItems[2].timestamp);
const idleStatus = {
isSyncing: false,
lastSyncAt: now - 120_000,
lastSyncDurationMs: 2_400,
lastSyncChats: 3,
lastError: null,
nextSyncAt: now + 1_800_000,
};
const server = setupServer();
function installMediaApi(items = mediaItems) {
server.use(
http.get('/api/media', () => HttpResponse.json(items)),
http.get('/api/media/sync', () => HttpResponse.json(idleStatus)),
);
}
function renderMedia() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
const view = render(
,
);
return { ...view, queryClient };
}
/** The card's footer toggle carries aria-pressed; the image button does not. */
function revealToggle(sender: string, pressed: boolean) {
return screen.getByRole('button', { name: `Reveal media from ${sender}`, pressed });
}
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => {
cleanup();
server.resetHandlers();
vi.restoreAllMocks();
});
afterAll(() => server.close());
describe('media page', () => {
it('loads authenticated media, keeps it blurred, and supports item and session-local reveals', async () => {
let resolveMedia: ((response: Response) => void) | undefined;
const credentials: RequestCredentials[] = [];
server.use(
http.get('/api/media', async ({ request }) => {
credentials.push(request.credentials);
return new Promise((resolve) => { resolveMedia = resolve; });
}),
http.get('/api/media/sync', ({ request }) => {
credentials.push(request.credentials);
return HttpResponse.json(idleStatus);
}),
);
const user = userEvent.setup();
const firstView = renderMedia();
expect(screen.getByRole('status', { name: 'Loading media' })).toBeInTheDocument();
await waitFor(() => expect(resolveMedia).toBeTypeOf('function'));
resolveMedia?.(HttpResponse.json(mediaItems));
const aliceImage = await screen.findByRole('img', { name: aliceAlt });
const charlieImage = screen.getByRole('img', { name: charlieAlt });
for (const profileLink of screen.getAllByRole('link', { name: 'alice' })) {
expect(profileLink).toHaveAttribute('href', 'https://www.reddit.com/u/alice');
}
expect(aliceImage).toHaveClass('is-blurred');
expect(charlieImage).toHaveClass('is-blurred');
expect(credentials.every((value) => value === 'same-origin')).toBe(true);
await user.click(revealToggle('alice', false));
expect(aliceImage).not.toHaveClass('is-blurred');
expect(charlieImage).toHaveClass('is-blurred');
await user.click(screen.getByRole('button', { name: 'Reveal all media' }));
expect(charlieImage).not.toHaveClass('is-blurred');
// Turning reveal-all back off keeps the earlier individual reveal intact.
await user.click(screen.getByRole('button', { name: 'Blur all media' }));
expect(charlieImage).toHaveClass('is-blurred');
expect(aliceImage).not.toHaveClass('is-blurred');
firstView.unmount();
installMediaApi();
renderMedia();
expect(await screen.findByRole('img', { name: aliceAlt })).toHaveClass('is-blurred');
});
it('reveals blurred media when its preview surface is clicked', async () => {
installMediaApi();
const user = userEvent.setup();
renderMedia();
const aliceImage = await screen.findByRole('img', { name: aliceAlt });
expect(aliceImage).toHaveClass('is-blurred');
// The image surface itself acts as a reveal control while blurred.
const imageButton = screen
.getAllByRole('button', { name: 'Reveal media from alice' })
.find((button) => button.classList.contains('media-preview-button'));
expect(imageButton).toBeDefined();
expect(imageButton).toBeEnabled();
await user.click(imageButton!);
expect(aliceImage).not.toHaveClass('is-blurred');
// Once revealed, the same surface opens the full-size preview instead.
await user.click(screen.getByRole('button', { name: 'View media from alice larger' }));
expect(screen.getByRole('dialog', { name: 'Media from alice' })).toBeInTheDocument();
});
it('opens revealed media in a dismissible full-size preview', async () => {
installMediaApi();
const user = userEvent.setup();
renderMedia();
await screen.findByRole('img', { name: aliceAlt });
await user.click(revealToggle('alice', false));
await user.click(screen.getByRole('button', { name: 'View media from alice larger' }));
const dialog = screen.getByRole('dialog', { name: 'Media from alice' });
expect(within(dialog).getByRole('img', { name: aliceAlt })).toHaveAttribute('src', '/media/one.jpg');
await user.keyboard('{Escape}');
expect(screen.queryByRole('dialog', { name: 'Media from alice' })).not.toBeInTheDocument();
});
it('navigates the preview across the visible items with buttons and arrow keys', async () => {
installMediaApi();
const user = userEvent.setup();
renderMedia();
await screen.findByRole('img', { name: aliceAlt });
await user.click(screen.getByRole('button', { name: 'Reveal all media' }));
await user.click(screen.getByRole('button', { name: 'View media from alice larger' }));
let dialog = screen.getByRole('dialog', { name: 'Media from alice' });
expect(within(dialog).getByRole('button', { name: 'Previous media' })).toBeDisabled();
expect(within(dialog).getByText('1 of 3')).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Next media' }));
dialog = screen.getByRole('dialog', { name: 'Media from charlie' });
expect(within(dialog).getByRole('img', { name: charlieAlt })).toHaveAttribute('src', '/media/two.gif');
expect(within(dialog).getByText('u/charlie')).toBeInTheDocument();
await user.keyboard('{ArrowRight}');
dialog = screen.getByRole('dialog', { name: 'Media from dave' });
expect(within(dialog).getByRole('button', { name: 'Next media' })).toBeDisabled();
await user.keyboard('{ArrowLeft}');
expect(screen.getByRole('dialog', { name: 'Media from charlie' })).toBeInTheDocument();
});
it('links media cards to their account-owned conversations', async () => {
installMediaApi();
renderMedia();
const conversationLinks = await screen.findAllByRole('link', { name: 'Open conversation' });
expect(conversationLinks).toHaveLength(3);
expect(conversationLinks[0]).toHaveAttribute(
'href',
'/conversations/%2540t2_bot%253Areddit.com~room-a',
);
expect(conversationLinks[1]).toHaveAttribute('href', '/conversations/room-b');
});
it('filters by conversation, sender, media type, and age with an explicit no-match state', async () => {
installMediaApi();
const user = userEvent.setup();
renderMedia();
expect(await screen.findAllByRole('img')).toHaveLength(3);
await user.selectOptions(screen.getByRole('combobox', { name: 'Conversation' }), 'alice');
expect(screen.getAllByRole('img')).toHaveLength(1);
expect(screen.getByRole('img', { name: aliceAlt })).toBeInTheDocument();
await user.selectOptions(screen.getByRole('combobox', { name: 'Conversation' }), 'all');
await user.selectOptions(screen.getByRole('combobox', { name: 'Sender' }), 'charlie');
expect(screen.getByRole('img', { name: charlieAlt })).toBeInTheDocument();
await user.selectOptions(screen.getByRole('combobox', { name: 'Sender' }), 'all');
await user.selectOptions(screen.getByRole('combobox', { name: 'Media type' }), 'gif');
expect(screen.getAllByRole('img')).toHaveLength(1);
await user.selectOptions(screen.getByRole('combobox', { name: 'Media type' }), 'all');
await user.selectOptions(screen.getByRole('combobox', { name: 'Date range' }), '7d');
expect(screen.getAllByRole('img')).toHaveLength(2);
await user.selectOptions(screen.getByRole('combobox', { name: 'Conversation' }), 'room-c');
expect(screen.getByText('No media matches these filters.')).toBeInTheDocument();
});
it('shows a result count and clears filters from both the panel and the empty state', async () => {
installMediaApi();
const user = userEvent.setup();
renderMedia();
await screen.findByRole('img', { name: aliceAlt });
expect(screen.getByText('Showing 3 of 3 items')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Clear filters' })).not.toBeInTheDocument();
await user.selectOptions(screen.getByRole('combobox', { name: 'Conversation' }), 'alice');
expect(screen.getByText('Showing 1 of 3 items')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Clear filters' }));
expect(screen.getAllByRole('img')).toHaveLength(3);
expect(screen.getByRole('combobox', { name: 'Conversation' })).toHaveValue('all');
await user.selectOptions(screen.getByRole('combobox', { name: 'Sender' }), 'charlie');
await user.selectOptions(screen.getByRole('combobox', { name: 'Media type' }), 'image');
const emptyState = screen.getByText('No media matches these filters.').closest('section');
expect(emptyState).not.toBeNull();
await user.click(within(emptyState!).getByRole('button', { name: 'Clear filters' }));
expect(screen.getAllByRole('img')).toHaveLength(3);
});
it('paginates large galleries behind a Load more control', async () => {
const manyItems = Array.from({ length: 60 }, (_, index) => ({
id: `item-${index}`, chatUsername: 'alice', chatRoomId: `room-${index}`, sender: 'alice',
timestamp: now - index * 60_000, originalUrl: `https://media.example/${index}.jpg`,
fileName: `${index}.jpg`, relativePath: `${index}.jpg`, createdAt: now - index * 60_000,
urlPath: `/media/${index}.jpg`,
}));
installMediaApi(manyItems);
const user = userEvent.setup();
renderMedia();
await screen.findByText('Showing 48 of 60 items');
expect(screen.getAllByRole('img')).toHaveLength(48);
await user.click(screen.getByRole('button', { name: 'Load more (12 remaining)' }));
expect(screen.getAllByRole('img')).toHaveLength(60);
expect(screen.getByText('Showing 60 of 60 items')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Load more/ })).not.toBeInTheDocument();
});
it('orders media by received time', async () => {
server.use(
http.get('/api/media', () => HttpResponse.json([mediaItems[2], mediaItems[0], mediaItems[1]])),
http.get('/api/media/sync', () => HttpResponse.json(idleStatus)),
);
renderMedia();
expect((await screen.findAllByRole('img')).map((item) => item.getAttribute('alt'))).toEqual([
aliceAlt,
charlieAlt,
daveAlt,
]);
});
it('shows empty and recoverable error states', async () => {
let requests = 0;
server.use(
http.get('/api/media', () => {
requests += 1;
return requests === 1
? HttpResponse.json({ error: 'Media index unavailable' }, { status: 500 })
: HttpResponse.json([]);
}),
http.get('/api/media/sync', () => HttpResponse.json(idleStatus)),
);
const user = userEvent.setup();
renderMedia();
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('Media index unavailable');
await user.click(within(alert).getByRole('button', { name: 'Retry media' }));
expect(await screen.findByText('No media yet.')).toBeInTheDocument();
expect(requests).toBe(2);
});
it('runs delta sync as the primary action and surfaces query-driven status and mutation outcomes', async () => {
installMediaApi();
let deltaRequests = 0;
server.use(
http.post('/api/media/sync', ({ request }) => {
deltaRequests += 1;
expect(request.credentials).toBe('same-origin');
return HttpResponse.json({ success: true });
}),
);
const user = userEvent.setup();
renderMedia();
const deltaButton = await screen.findByRole('button', { name: 'Sync new media' });
expect(deltaButton).toHaveClass('primary');
expect(screen.getByText('Last synced 3 conversations')).toBeInTheDocument();
await user.click(deltaButton);
expect(await screen.findByText('Media sync completed.')).toBeInTheDocument();
expect(deltaRequests).toBe(1);
server.use(
http.post('/api/media/sync', () => HttpResponse.json({ success: false, reason: 'Sync already in progress' })),
);
await user.click(screen.getByRole('button', { name: 'Sync new media' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Sync already in progress');
});
it('auto-dismisses the sync success notice after five seconds', async () => {
installMediaApi();
server.use(http.post('/api/media/sync', () => HttpResponse.json({ success: true })));
const user = userEvent.setup();
renderMedia();
await user.click(await screen.findByRole('button', { name: 'Sync new media' }));
const notice = await screen.findByText('Media sync completed.');
expect(notice).toHaveAttribute('role', 'status');
await waitFor(
() => expect(screen.queryByText('Media sync completed.')).not.toBeInTheDocument(),
{ timeout: 7_000 },
);
}, 15_000);
it('refreshes shared sync status as soon as a long-running mutation starts', async () => {
let statusRequests = 0;
let resolveSync: ((response: Response) => void) | undefined;
server.use(
http.get('/api/media', () => HttpResponse.json(mediaItems)),
http.get('/api/media/sync', () => {
statusRequests += 1;
return HttpResponse.json(statusRequests === 1 ? idleStatus : { ...idleStatus, isSyncing: true });
}),
http.post('/api/media/sync', async () =>
new Promise((resolve) => { resolveSync = resolve; }),
),
);
const user = userEvent.setup();
renderMedia();
await user.click(await screen.findByRole('button', { name: 'Sync new media' }));
expect(await screen.findByText('Media sync in progress')).toBeInTheDocument();
expect(statusRequests).toBeGreaterThan(1);
resolveSync?.(HttpResponse.json({ success: true }));
await waitFor(() => expect(screen.getByText('Media sync completed.')).toBeInTheDocument());
});
it('guards a full sync with explicit confirmation', async () => {
installMediaApi();
let fullRequests = 0;
server.use(
http.post('/api/media/sync/full', () => {
fullRequests += 1;
return HttpResponse.json({ success: true });
}),
);
const user = userEvent.setup();
renderMedia();
await user.click(await screen.findByRole('button', { name: 'Full sync' }));
const dialog = screen.getByRole('dialog', { name: 'Run full media sync?' });
expect(dialog).toHaveTextContent('every conversation');
expect(fullRequests).toBe(0);
await user.click(within(dialog).getByRole('button', { name: 'Cancel' }));
expect(fullRequests).toBe(0);
await user.click(screen.getByRole('button', { name: 'Full sync' }));
await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Run full sync' }));
expect(await screen.findByText('Full media sync completed.')).toBeInTheDocument();
expect(fullRequests).toBe(1);
});
it('closes the full-sync dialog so a failed mutation is clearly visible', async () => {
installMediaApi();
server.use(
http.post('/api/media/sync/full', () =>
HttpResponse.json({ error: 'Full sync could not reach Reddit' }, { status: 500 }),
),
);
const user = userEvent.setup();
renderMedia();
await user.click(await screen.findByRole('button', { name: 'Full sync' }));
await user.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Run full sync' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Full sync could not reach Reddit');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});