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
12 changes: 11 additions & 1 deletion frontend/src/features/wine/WinePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { LocationProbe } from '../../test/LocationProbe';
import { WINE_REVIEWS_QUERY } from './api/reviewQueries';
import { WINE_QUERY } from './api/wineQuery';
import WinePage from './WinePage';
import { SEARCH_WINES_QUERY } from '../search/api/searchQuery';

const wine = {
__typename: 'Wine',
Expand Down Expand Up @@ -66,14 +67,23 @@ const noReviews = (): MockLink.MockedResponse => ({
},
});

/** The similar wines section asks for its own data. These tests are about the rest of the page. */
const noSimilar = (): MockLink.MockedResponse => ({
request: {
query: SEARCH_WINES_QUERY,
variables: { filter: { grapes: ['Merlot'] }, sort: 'TOP_RATED', first: 5 },
},
result: { data: { wines: { __typename: 'WineConnection', edges: [] } } },
});

function renderPage(
mocks: MockLink.MockedResponse[],
entry: string | { pathname: string; state: unknown } = '/vin/100062',
) {
window.localStorage.setItem(USER_ID_KEY, USER_ID);
const user = userEvent.setup();
const result = render(
<MockedProvider mocks={[...mocks, noReviews()]} cache={createApolloCache()}>
<MockedProvider mocks={[...mocks, noReviews(), noSimilar()]} cache={createApolloCache()}>
<MemoryRouter initialEntries={[entry]}>
<Routes>
<Route path="vin/:id" element={<WinePage />} />
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/features/wine/WineView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { WINE_TYPES, wineTypeToken } from '../../lib/wineTypes';
import type { WineResult } from './api/useWine';
import { StudentReviews } from './components/StudentReviews';
import styles from './WineView.module.css';
import { SimilarWines } from './components/SimilarWines';

type WineViewProps = WineResult & { notFound: boolean };

Expand Down Expand Up @@ -145,6 +146,7 @@ function WineDetailsView({ wine }: { wine: WineDetails }) {
)}

<StudentReviews wineId={wine.id} />
<SimilarWines wine={wine} />
</article>
);
}
Expand Down
30 changes: 30 additions & 0 deletions frontend/src/features/wine/api/useSimilarWines.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useQuery } from '@apollo/client/react';
import { SEARCH_WINES_QUERY } from '../../search/api/searchQuery';
import { toApiWineType, toWineSummary, type ApiWine } from '../../../lib/mapWine';
import type { WineDetails, WineSummary } from '../../../lib/types';

/** How many wines to show. We ask for more, since the wine itself is in the result. */
const SHOW = 4;

interface SearchData {
wines: { edges: { node: ApiWine }[] };
}

/**
* Wines like this one: the same grape when we know it, otherwise the same type.
* Uses the search query, so the database does the work and nothing new is needed in the API.
*/
export function useSimilarWines(wine: WineDetails | null): WineSummary[] {
const grape = wine?.grapes[0];
const filter = grape ? { grapes: [grape] } : wine ? { types: [toApiWineType(wine.type)] } : null;

const { data } = useQuery<SearchData>(SEARCH_WINES_QUERY, {
variables: { filter, sort: 'TOP_RATED', first: SHOW + 1 },
skip: !filter,
});

return (data?.wines.edges ?? [])
.map(({ node }) => toWineSummary(node))
.filter((similar): similar is WineSummary => similar !== null && similar.id !== wine?.id)
.slice(0, SHOW);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.section {
display: grid;
gap: var(--space-3);
min-width: 0;
}

.note {
color: var(--color-text-muted);
}
162 changes: 162 additions & 0 deletions frontend/src/features/wine/components/SimilarWines.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { describe, expect, it } from 'vitest';
import { render, screen, within } from '@testing-library/react';
import type { MockLink } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing/react';
import { MemoryRouter } from 'react-router';
import { axe } from 'vitest-axe';
import { createApolloCache } from '../../../lib/apollo';
import type { WineDetails } from '../../../lib/types';
import { SEARCH_WINES_QUERY } from '../../search/api/searchQuery';
import { SimilarWines } from './SimilarWines';

const WINE: WineDetails = {
id: '100062',
name: 'Origem Merlot',
winery: 'Casa Valduga',
country: 'Brasil',
type: 'RED',
grapes: ['Merlot', 'Tannat'],
community: { average: 4.1, count: 12 },
students: null,
region: 'Vale dos Vinhedos',
abv: 13,
body: 'Fyldig',
acidity: 'Middels',
style: null,
foods: [],
vintages: null,
website: null,
};

const apiWine = (id: string, name: string) => ({
__typename: 'Wine',
id,
name,
type: 'Red',
grapes: ['Merlot'],
country: 'Italy',
countryCode: 'IT',
wineryName: 'Produsent',
communityRating: 4,
communityRatingCount: 10,
});

/** One answer to the query the section sends for a wine with Merlot. */
function similar(wines: { id: string; name: string }[]): MockLink.MockedResponse {
return {
request: {
query: SEARCH_WINES_QUERY,
variables: { filter: { grapes: ['Merlot'] }, sort: 'TOP_RATED', first: 5 },
},
result: {
data: {
wines: {
__typename: 'WineConnection',
totalCount: wines.length,
edges: wines.map(({ id, name }) => ({
__typename: 'WineEdge',
cursor: id,
node: apiWine(id, name),
})),
pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null },
},
},
},
};
}

function renderSimilar(mocks: MockLink.MockedResponse[], wine = WINE) {
return render(
<MockedProvider mocks={mocks} cache={createApolloCache()}>
<MemoryRouter>
<SimilarWines wine={wine} />
</MemoryRouter>
</MockedProvider>,
);
}

const list = () => screen.findByRole('list', { name: 'Liknende viner' });

describe('SimilarWines', () => {
it('shows wines with the same grape, and names the grape', async () => {
renderSimilar([
similar([
{ id: '1', name: 'Chianti' },
{ id: '2', name: 'Barolo' },
]),
]);

expect(within(await list()).getAllByRole('listitem')).toHaveLength(2);
expect(screen.getByText('Andre viner med Merlot.')).toBeInTheDocument();
});

it('never shows the wine the user is already looking at', async () => {
renderSimilar([
similar([
{ id: '100062', name: 'Origem Merlot' },
{ id: '1', name: 'Chianti' },
]),
]);

const items = within(await list()).getAllByRole('listitem');
expect(items).toHaveLength(1);
expect(screen.queryByRole('link', { name: 'Origem Merlot' })).not.toBeInTheDocument();
});

it('shows at most four wines', async () => {
renderSimilar([similar(['1', '2', '3', '4', '5'].map((id) => ({ id, name: `Vin ${id}` })))]);

expect(within(await list()).getAllByRole('listitem')).toHaveLength(4);
});

it('shows nothing when there are no similar wines', () => {
const { container } = renderSimilar([similar([])]);
expect(container).toBeEmptyDOMElement();
});

it('shows nothing when the request fails, since this is extra', async () => {
const { container } = renderSimilar([
{
request: {
query: SEARCH_WINES_QUERY,
variables: { filter: { grapes: ['Merlot'] }, sort: 'TOP_RATED', first: 5 },
},
error: new Error('Nede'),
},
]);

await new Promise((resolve) => setTimeout(resolve, 0));
expect(container).toBeEmptyDOMElement();
});

it('falls back to the wine type when the grape is unknown', async () => {
renderSimilar(
[
{
request: {
query: SEARCH_WINES_QUERY,
variables: { filter: { types: ['Red'] }, sort: 'TOP_RATED', first: 5 },
},
result: {
data: {
wines: {
__typename: 'WineConnection',
edges: [{ __typename: 'WineEdge', node: apiWine('1', 'Chianti') }],
},
},
},
},
],
{ ...WINE, grapes: [] },
);

expect(within(await list()).getAllByRole('listitem')).toHaveLength(1);
expect(screen.getByText('Andre viner av samme type.')).toBeInTheDocument();
});

it('has no axe violations', async () => {
const { container } = renderSimilar([similar([{ id: '1', name: 'Chianti' }])]);
await list();
expect(await axe(container)).toHaveNoViolations();
});
});
22 changes: 22 additions & 0 deletions frontend/src/features/wine/components/SimilarWines.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { WineList } from '../../../components/ui/WineList';
import { useSimilarWines } from '../api/useSimilarWines';
import type { WineDetails } from '../../../lib/types';
import styles from './SimilarWines.module.css';

/** A few wines like this one. Hidden when there is nothing to show. */
export function SimilarWines({ wine }: { wine: WineDetails }) {
const wines = useSimilarWines(wine);
if (wines.length === 0) return null;

const grape = wine.grapes[0];

return (
<section className={styles.section} aria-labelledby="similar-title">
<h2 id="similar-title">Liknende viner</h2>
<p className={styles.note}>
{grape ? `Andre viner med ${grape}.` : 'Andre viner av samme type.'}
</p>
<WineList wines={wines} headingLevel="h3" label="Liknende viner" />
</section>
);
}