Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 78 additions & 51 deletions frontend/src/features/search/SearchPage.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ServerError } from '@apollo/client/errors';
Expand All @@ -12,6 +12,7 @@ import { LocationProbe } from '../../test/LocationProbe';
import { searchMock, type SentVariables } from '../../test/searchMocks';
import { SEARCH_WINES_QUERY } from './api/searchQuery';
import SearchPage from './SearchPage';
import { SEARCH_DEBOUNCE_MS } from './useSearchText';

const router: { navigate?: ReturnType<typeof useNavigate> } = {};
const navigate = (to: string | number) => router.navigate?.(to as string);
Expand All @@ -24,8 +25,12 @@ function NavigateProbe() {
return null;
}

function renderPage(mocks: MockLink.MockedResponse[], route = '/sok') {
const user = userEvent.setup();
function renderPage(
mocks: MockLink.MockedResponse[],
route = '/sok',
userOptions: Parameters<typeof userEvent.setup>[0] = {},
) {
const user = userEvent.setup(userOptions);
const result = render(
<MockedProvider mocks={mocks} cache={createApolloCache()}>
<MemoryRouter initialEntries={['/', route]} initialIndex={1}>
Expand All @@ -45,16 +50,16 @@ const searchbox = () => screen.getByRole('searchbox', { name: 'Søk etter vin' }
const results = () => screen.findByRole('list', { name: 'Søkeresultater' });
const status = () => screen.getByRole('status');

describe('SearchPage – resultater', () => {
it('viser alle viner når det ikke er søkt', async () => {
describe('SearchPage – results', () => {
it('shows all wines when there is no search', async () => {
renderPage([searchMock(() => 5).mock]);
expect(within(await results()).getAllByRole('article')).toHaveLength(2);
expect(screen.getByRole('heading', { level: 1, name: 'Utforsk viner' })).toBeInTheDocument();
expect(status()).toHaveTextContent('Viser 2 av 5 viner');
expect(document.title).toBe('Utforsk viner – Kork & Krone');
});

it('søker etter ordet i URL-en og viser det i feltet', async () => {
it('searches for the word in the URL and shows it in the field', async () => {
const { mock, resolver } = searchMock(() => 1);
renderPage([mock], '/sok?q=pinot');
await results();
Expand All @@ -64,7 +69,7 @@ describe('SearchPage – resultater', () => {
expect(document.title).toBe('Søk: pinot – Kork & Krone');
});

it('bruker filtre fra URL-en, slik at snarveiene på forsiden virker', async () => {
it('uses filters from the URL, so the shortcuts on the landing page work', async () => {
const { mock, resolver } = searchMock(() => 1);
renderPage([mock], '/sok?type=rodvin&land=IT');
await results();
Expand All @@ -73,20 +78,20 @@ describe('SearchPage – resultater', () => {
);
});

it('bruker vinnavnet som overskrift under h1', async () => {
it('uses the wine name as a heading below the h1', async () => {
renderPage([searchMock(() => 1).mock]);
await results();
expect(screen.getByRole('heading', { level: 2, name: 'Vin 1' })).toBeInTheDocument();
});

it('ignorerer ugyldige verdier i URL-en', async () => {
it('ignores invalid values in the URL', async () => {
const { mock, resolver } = searchMock(() => 1);
renderPage([mock], '/sok?type=ukjent&sort=hack');
await results();
expect(resolver).toHaveBeenCalledWith({ sort: 'TOP_RATED', first: 24 });
});

it('tåler spesialtegn i søket', async () => {
it('handles special characters in the search', async () => {
const { mock, resolver } = searchMock(() => 1);
renderPage([mock], `/sok?q=${encodeURIComponent('100% "rosé" <b>')}`);
await results();
Expand All @@ -95,77 +100,99 @@ describe('SearchPage – resultater', () => {
});
});

describe('SearchPage – skriving i søkefeltet', () => {
it('sender ett søk etter at brukeren har skrevet ferdig', async () => {
describe('SearchPage – typing in the search field', () => {
/*
* The field waits SEARCH_DEBOUNCE_MS after the last key press. With real time, a busy machine
* (for example during `npm run check`) can pause longer than that between two key presses,
* which sent an extra search and made these tests fail now and then. Here the test decides
* when the pause is over:
* - fake timers, so the debounce only runs out when the test moves the clock;
* - shouldAdvanceTime, so Testing Library and Apollo's mocks, which wait with setTimeout,
* still get their time;
* - delay: null, so user-event types a whole word without a pause the clock could use.
*/
beforeEach(() => vi.useFakeTimers({ shouldAdvanceTime: true }));
afterEach(() => vi.useRealTimers());

const renderTyping = (mocks: MockLink.MockedResponse[], route?: string) =>
renderPage(mocks, route, { delay: null });

/** The user stops typing: the debounce runs out and the URL is updated. */
const pause = () => act(() => vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS));

const currentUrl = () => screen.getByTestId('location');

it('sends one search once the user has finished typing', async () => {
const { mock, resolver } = searchMock(() => 1);
const { user } = renderPage([mock]);
const { user } = renderTyping([mock]);
await results();
resolver.mockClear();

await user.type(searchbox(), 'pinot');
await pause();

await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/sok?q=pinot'));
expect(currentUrl()).toHaveTextContent('/sok?q=pinot');
await waitFor(() => expect(resolver).toHaveBeenCalled());
expect(resolver).toHaveBeenCalledOnce();
expect(resolver).toHaveBeenCalledWith(expect.objectContaining({ search: 'pinot' }));
});

it('søker med en gang ved Enter', async () => {
it('searches at once on Enter', async () => {
const { mock } = searchMock(() => 1);
const { user } = renderPage([mock]);
const { user } = renderTyping([mock]);
await results();

await user.type(searchbox(), 'merlot{Enter}');

expect(screen.getByTestId('location')).toHaveTextContent('/sok?q=merlot');
});

it('beholder mellomrommet mens brukeren skriver neste ord', async () => {
const { user } = renderPage([searchMock(() => 1).mock], '/sok?q=pinot');
it('keeps the space while the user types the next word', async () => {
const { user } = renderTyping([searchMock(() => 1).mock], '/sok?q=pinot');
await results();

await user.type(searchbox(), ' ');
await new Promise((resolve) => setTimeout(resolve, 400));
await pause();
await user.type(searchbox(), 'noir');

expect(searchbox()).toHaveValue('pinot noir');
});

it('sender ikke et nytt søk for bare mellomrom', async () => {
it('sends no new search for spaces only', async () => {
const { mock, resolver } = searchMock(() => 1);
const { user } = renderPage([mock]);
const { user } = renderTyping([mock]);
await results();
resolver.mockClear();

await user.type(searchbox(), ' ');
await new Promise((resolve) => setTimeout(resolve, 400));
await pause();

expect(resolver).not.toHaveBeenCalled();
expect(screen.getByTestId('location')).toHaveTextContent(/^\/sok$/);
expect(currentUrl()).toHaveTextContent(/^\/sok$/);
});

it('viser alle viner igjen når feltet tømmes', async () => {
const { user } = renderPage([searchMock(() => 1).mock], '/sok?q=pinot');
it('shows all wines again when the field is cleared', async () => {
const { user } = renderTyping([searchMock(() => 1).mock], '/sok?q=pinot');
await results();

await user.clear(searchbox());
await pause();

await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent(/^\/sok$/));
expect(currentUrl()).toHaveTextContent(/^\/sok$/);
});

it('beholder filtrene når søket endres', async () => {
const { user } = renderPage([searchMock(() => 1).mock], '/sok?type=rodvin');
it('keeps the filters when the search changes', async () => {
const { user } = renderTyping([searchMock(() => 1).mock], '/sok?type=rodvin');
await results();

await user.type(searchbox(), 'pinot');
await pause();

await waitFor(() =>
expect(screen.getByTestId('location')).toHaveTextContent('/sok?q=pinot&type=rodvin'),
);
expect(currentUrl()).toHaveTextContent('/sok?q=pinot&type=rodvin');
});

it('fyller ikke historikken med et innslag per søk', async () => {
const { user } = renderPage([searchMock(() => 1).mock]);
it('does not add a history entry per search', async () => {
const { user } = renderTyping([searchMock(() => 1).mock]);
await results();
await user.type(searchbox(), 'pinot{Enter}');

Expand All @@ -174,34 +201,34 @@ describe('SearchPage – skriving i søkefeltet', () => {
await screen.findByText('Annen side');
});

it('oppdaterer feltet når URL-en endres utenfra', async () => {
renderPage([searchMock(() => 1).mock], '/sok?q=pinot');
it('updates the field when the URL changes from outside', async () => {
renderTyping([searchMock(() => 1).mock], '/sok?q=pinot');
await results();

act(() => void navigate('/sok?q=merlot'));

await waitFor(() => expect(searchbox()).toHaveValue('merlot'));
});

it('sender ikke søket etter at brukeren har forlatt siden', async () => {
it('does not send the search after the user has left the page', async () => {
const { mock, resolver } = searchMock(() => 1);
const { user } = renderPage([mock]);
const { user } = renderTyping([mock]);
await results();
resolver.mockClear();

await user.type(searchbox(), 'pinot');
act(() => void navigate('/mine'));
await new Promise((resolve) => setTimeout(resolve, 400));
await pause();

expect(screen.getByTestId('location')).toHaveTextContent('/mine');
expect(currentUrl()).toHaveTextContent('/mine');
expect(resolver).not.toHaveBeenCalled();
});
});

describe('SearchPage – last inn flere', () => {
describe('SearchPage – load more', () => {
const loadMore = () => screen.getByRole('button', { name: 'Last inn flere' });

it('legger neste side til under de første vinene', async () => {
it('adds the next page below the first wines', async () => {
const { user } = renderPage([searchMock(() => 3).mock]);
await results();

Expand All @@ -212,7 +239,7 @@ describe('SearchPage – last inn flere', () => {
expect(screen.getByRole('link', { name: 'Vin 3' })).toBeInTheDocument();
});

it('flytter fokus til den første nye vinen', async () => {
it('moves focus to the first new wine', async () => {
const { user } = renderPage([searchMock(() => 3).mock]);
await results();

Expand All @@ -221,13 +248,13 @@ describe('SearchPage – last inn flere', () => {
await waitFor(() => expect(screen.getByRole('link', { name: 'Vin 3' })).toHaveFocus());
});

it('skjuler knappen når alle viner er vist', async () => {
it('hides the button when all wines are shown', async () => {
renderPage([searchMock(() => 2).mock]);
await results();
expect(screen.queryByRole('button', { name: 'Last inn flere' })).not.toBeInTheDocument();
});

it('beholder vinene og tilbyr nytt forsøk når lastingen feiler', async () => {
it('keeps the wines and offers a retry when loading fails', async () => {
const first = searchMock(() => 3).mock;
const failing: MockLink.MockedResponse = {
request: {
Expand All @@ -248,26 +275,26 @@ describe('SearchPage – last inn flere', () => {
});
});

describe('SearchPage – tilstander', () => {
it('viser lastetilstand i live-regionen', () => {
describe('SearchPage – states', () => {
it('shows the loading state in the live region', () => {
renderPage([searchMock(() => 1).mock]);
expect(status()).toHaveTextContent('Søker');
expect(screen.getAllByTestId('skeleton').length).toBeGreaterThan(0);
});

it('forklarer når søket ikke gir treff, og lenker til alle viner', async () => {
it('explains when the search has no hits, and links to all wines', async () => {
renderPage([searchMock(() => 0).mock], '/sok?q=finnesikke');
expect(await screen.findByText(/Ingen viner passer til/)).toHaveTextContent('«finnesikke»');
expect(status()).toHaveTextContent('Ingen treff');
expect(screen.getByRole('link', { name: 'Se alle viner' })).toHaveAttribute('href', '/sok');
});

it('viser en egen tekst når filtre uten søkeord ikke gir treff', async () => {
it('shows its own text when filters without a search word have no hits', async () => {
renderPage([searchMock(() => 0).mock], '/sok?type=rodvin');
expect(await screen.findByText('Ingen viner passer til valgene dine.')).toBeInTheDocument();
});

it('viser feilmelding og kan prøve igjen', async () => {
it('shows an error and can try again', async () => {
const failing: MockLink.MockedResponse = {
request: { query: SEARCH_WINES_QUERY, variables: () => true },
error: new ServerError('Service Unavailable', {
Expand All @@ -286,13 +313,13 @@ describe('SearchPage – tilstander', () => {
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});

it('har ingen axe-brudd med resultater', async () => {
it('has no axe violations with results', async () => {
const { container } = renderPage([searchMock(() => 3).mock]);
await results();
expect(await axe(container)).toHaveNoViolations();
});

it('har ingen axe-brudd uten treff', async () => {
it('has no axe violations without hits', async () => {
const { container } = renderPage([searchMock(() => 0).mock], '/sok?q=x');
await screen.findByText(/Ingen viner passer til/);
expect(await axe(container)).toHaveNoViolations();
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/features/search/useSearchText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router';
import { parseSearchParams, toSearchParams } from '../../lib/searchParams';

const DEBOUNCE_MS = 300;
/** How long the field waits after the last key press before it searches. Exported for the tests. */
export const SEARCH_DEBOUNCE_MS = 300;

const normalize = (text: string) => text.trim().replace(/\s+/g, ' ');

Expand Down Expand Up @@ -33,7 +34,7 @@ export function useSearchText() {
if (normalize(text) === urlText) return;
const timer = setTimeout(() => {
setParams(toSearchParams({ ...parseSearchParams(params), q: text }), { replace: true });
}, DEBOUNCE_MS);
}, SEARCH_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [text, urlText, params, setParams]);

Expand Down