Files
ersatztv/web/src/api/search.test.ts
T

116 lines
3.2 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getSearchAllItems, getSearchResults, toAddItemsRequestFromSearch } from './search';
const emptyGroup = { totalCount: 0, items: [] };
const sampleResults = {
movies: emptyGroup,
shows: emptyGroup,
seasons: emptyGroup,
artists: emptyGroup,
episodes: emptyGroup,
musicVideos: emptyGroup,
songs: emptyGroup,
otherVideos: emptyGroup,
images: emptyGroup,
remoteStreams: emptyGroup
};
describe('getSearchResults', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('GETs /api/search with the query', async () => {
const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(
new Response(JSON.stringify(sampleResults), {
headers: { 'Content-Type': 'application/json' },
status: 200
})
);
await getSearchResults({ query: 'star' });
const [url, init] = fetchSpy.mock.calls[0];
expect(url).toBe('/api/search?query=star');
expect((init?.method ?? 'GET').toUpperCase()).toBe('GET');
});
it('includes pageSize when provided', async () => {
const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(
new Response(JSON.stringify(sampleResults), {
headers: { 'Content-Type': 'application/json' },
status: 200
})
);
await getSearchResults({ query: 'star wars', pageSize: 50 });
const [url] = fetchSpy.mock.calls[0];
expect(url).toBe('/api/search?query=star+wars&pageSize=50');
});
it('rejects with the ApiError status on failure', async () => {
vi.spyOn(window, 'fetch').mockResolvedValue(
new Response(JSON.stringify({ status: 422, title: 'Validation failed' }), {
headers: { 'Content-Type': 'application/json' },
status: 422
})
);
await expect(getSearchResults({ query: '' })).rejects.toMatchObject({ status: 422 });
});
});
describe('getSearchAllItems', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('GETs /api/search/all-items with the query', async () => {
const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue(
new Response(JSON.stringify({ movieIds: [1], showIds: [2] }), {
headers: { 'Content-Type': 'application/json' },
status: 200
})
);
await getSearchAllItems('star wars');
const [url, init] = fetchSpy.mock.calls[0];
expect(url).toBe('/api/search/all-items?query=star+wars');
expect((init?.method ?? 'GET').toUpperCase()).toBe('GET');
});
});
describe('toAddItemsRequestFromSearch', () => {
it('fills every bucket, defaulting null arrays to []', () => {
expect(
toAddItemsRequestFromSearch({
artistIds: null,
episodeIds: null,
imageIds: null,
movieIds: [1, 2],
musicVideoIds: null,
otherVideoIds: null,
remoteStreamIds: null,
seasonIds: null,
showIds: null,
songIds: null
})
).toEqual({
artistIds: [],
episodeIds: [],
imageIds: [],
movieIds: [1, 2],
musicVideoIds: [],
otherVideoIds: [],
remoteStreamIds: [],
seasonIds: [],
showIds: [],
songIds: []
});
});
});