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
3 changes: 3 additions & 0 deletions frontend/src/features/wine/api/useWineReviews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export interface WineReviewsResult {
reviews: ApiReview[];
distribution: RatingCount[];
myReview: WineReviewsData['myReview'];
/** True once the reviews have been fetched. Stays true while they are fetched again. */
hasData: boolean;
loading: boolean;
error: Error | undefined;
refetch: () => void;
Expand Down Expand Up @@ -83,6 +85,7 @@ export function useWineReviews(wineId: string): WineReviewsResult {
reviews: data?.wine?.reviews ?? [],
distribution: data?.wine?.ratingDistribution ?? [],
myReview: data?.myReview ?? null,
hasData: data !== undefined,
loading,
error,
// A failed retry already shows up in `error`, so the rejected promise needs no handling.
Expand Down
28 changes: 24 additions & 4 deletions frontend/src/features/wine/components/StudentReviews.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@
align-content: start;
gap: var(--space-4);
min-width: 0;
position: relative;
grid-auto-flow: row;
}

.summary {
font-size: var(--text-lg);
font-weight: 600;
}

.message:empty {
display: none;
}

.list {
display: grid;
gap: var(--space-3);
Expand Down Expand Up @@ -52,3 +50,25 @@
.subtitle {
font-size: var(--text-lg);
}

.message {
font-weight: 600;
}

/*
* Empty: keep it in the DOM and in the accessibility tree, but out of the grid, so it
* adds no gap. Absolutely positioned children are not grid items. `display: none`
* would take it out of the accessibility tree, and the message would never be announced.
*/
.message:empty {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
}

.message {
font-weight: 600;
order: 1;
}
170 changes: 170 additions & 0 deletions frontend/src/features/wine/components/StudentReviews.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { describe, expect, it } from 'vitest';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { MockLink } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing/react';
import { axe } from 'vitest-axe';
import { USER_ID_KEY } from '../../../hooks/useUserId';
import { createApolloCache } from '../../../lib/apollo';
import {
DELETE_REVIEW_MUTATION,
SAVE_REVIEW_MUTATION,
WINE_REVIEWS_QUERY,
} from '../api/reviewQueries';
import { StudentReviews } from './StudentReviews';

const WINE_ID = '100062';
const USER_ID = '3f2a9c1e-8b4d-4e2a-9f1c-2b7d6e5a4c3b';
const NOW = new Date('2026-11-13T12:00:00.000Z');

const review = (rating: number, comment: string | null, id = 'r1') => ({
__typename: 'Review',
id,
rating,
comment,
author: 'Student #1',
updatedAt: '2026-11-13T11:00:00.000Z',
});

/** One answer to the reviews query: the wine's reviews and the user's own review. */
function reviews(
list: ReturnType<typeof review>[],
mine: { id: string; rating: number; comment: string | null } | null = null,
distribution: { rating: number; count: number }[] = [],
): MockLink.MockedResponse {
const ratings = list.map((r) => r.rating);
return {
request: { query: WINE_REVIEWS_QUERY, variables: { id: WINE_ID, userId: USER_ID } },
result: {
data: {
wine: {
__typename: 'Wine',
id: WINE_ID,
studentRating: {
__typename: 'StudentRating',
average: ratings.length ? ratings.reduce((a, b) => a + b, 0) / ratings.length : null,
count: ratings.length,
},
ratingDistribution: distribution.map((d) => ({ __typename: 'RatingCount', ...d })),
reviews: list,
},
myReview: mine && { __typename: 'Review', ...mine },
},
},
};
}

function renderReviews(mocks: MockLink.MockedResponse[]) {
window.localStorage.setItem(USER_ID_KEY, USER_ID);
const user = userEvent.setup();
const result = render(
<MockedProvider mocks={mocks} cache={createApolloCache()}>
<StudentReviews wineId={WINE_ID} now={NOW} />
</MockedProvider>,
);
return { user, ...result };
}

/** The reviews are in an <ol>, the distribution in a <ul>, so this picks the reviews. */
const reviewList = () => screen.findByRole('list', { name: 'Studentenes dommer' });

describe('StudentReviews', () => {
it('shows the average, the distribution and the newest reviews', async () => {
renderReviews([
reviews([review(4, 'God til pizza'), review(3, null, 'r2')], null, [
{ rating: 4, count: 1 },
{ rating: 3, count: 1 },
]),
]);

expect(await screen.findByText(/av 5 · 2 dommer/)).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Alle vurderinger' })).toBeInTheDocument();
expect(within(await reviewList()).getAllByRole('listitem')).toHaveLength(2);
expect(screen.getByText('God til pizza')).toBeInTheDocument();
});

it('explains when nobody has reviewed the wine', async () => {
renderReviews([reviews([])]);
expect(await screen.findByText(/Ingen studenter har dømt denne vinen/)).toBeInTheDocument();
});

it('saves a review and reports it in a live region that screen readers follow', async () => {
const saved = { id: 'r9', rating: 3.5, comment: null };
const { user } = renderReviews([
reviews([]),
{
request: {
query: SAVE_REVIEW_MUTATION,
variables: { input: { wineId: WINE_ID, userId: USER_ID, rating: 3.5, comment: null } },
},
result: { data: { saveReview: { __typename: 'Review', ...saved } } },
},
reviews([review(3.5, null, 'r9')], saved),
]);

await user.click(await screen.findByRole('radio', { name: '3,5 av 5 stjerner' }));

// The live region must already be in the DOM, or the message is never announced.
const status = screen.getByRole('status');
expect(status).toBeEmptyDOMElement();

await user.click(screen.getByRole('button', { name: 'Lagre dommen' }));

expect(await screen.findByRole('button', { name: 'Oppdater dommen' })).toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent('Dommen er lagret.');
});

it('tells the user when saving fails', async () => {
const { user } = renderReviews([
reviews([]),
{
request: {
query: SAVE_REVIEW_MUTATION,
variables: { input: { wineId: WINE_ID, userId: USER_ID, rating: 5, comment: null } },
},
error: new Error('Nede'),
},
]);

await user.click(await screen.findByRole('radio', { name: '5 av 5 stjerner' }));
await user.click(screen.getByRole('button', { name: 'Lagre dommen' }));

await waitFor(() =>
expect(screen.getByRole('status')).toHaveTextContent('Vi fikk ikke lagret dommen'),
);
});

it('deletes the user\u2019s own review', async () => {
const mine = { id: 'r1', rating: 4, comment: 'God' };
const { user } = renderReviews([
reviews([review(4, 'God')], mine),
{
request: { query: DELETE_REVIEW_MUTATION, variables: { wineId: WINE_ID, userId: USER_ID } },
result: { data: { deleteReview: true } },
},
reviews([]),
]);

await user.click(await screen.findByRole('button', { name: 'Slett dommen' }));
await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('Dommen er slettet.'));
});

it('offers a new attempt when the reviews cannot be fetched', async () => {
renderReviews([
{
request: { query: WINE_REVIEWS_QUERY, variables: { id: WINE_ID, userId: USER_ID } },
error: new Error('Nede'),
},
]);
expect(await screen.findByRole('alert')).toHaveTextContent('Vi fikk ikke hentet dommene');
expect(screen.getByRole('button', { name: 'Prøv igjen' })).toBeInTheDocument();
});

it('has no axe violations', async () => {
const { container } = renderReviews([
reviews([review(4, 'God')], null, [{ rating: 4, count: 1 }]),
]);
await reviewList();
expect(await axe(container)).toHaveNoViolations();
});
});
30 changes: 20 additions & 10 deletions frontend/src/features/wine/components/StudentReviews.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) {
reviews,
distribution,
myReview,
hasData,
loading,
error,
refetch,
Expand All @@ -46,14 +47,28 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) {
<section className={styles.section} aria-labelledby="students-title">
<h2 id="students-title">Vurderinger</h2>

{loading && <Skeleton rows={1} tall={false} />}
{/*
* Outside every condition, so this element is never replaced. A live region that
* is removed and built again is not announced by screen readers.
*/}
<p role="status" className={styles.message}>
{message}
</p>

{error && <ErrorNotice message="Vi fikk ikke hentet dommene akkurat nå." onRetry={refetch} />}
{/* Only on the first load. A later fetch keeps the content, so focus stays where it is. */}
{loading && !hasData && <Skeleton rows={1} tall={false} />}

{!loading && !error && (
{/* A failed fetch after the first one keeps the content; the live region reports the failure. */}
{error && !hasData && (
<ErrorNotice message="Vi fikk ikke hentet dommene akkurat nå." onRetry={refetch} />
)}

{hasData && (
<>
<RatingDistribution distribution={distribution} />
<h3 className={styles.subtitle}>Studentenes dommer</h3>
<h3 id="student-reviews-title" className={styles.subtitle}>
Studentenes dommer
</h3>

<p className={styles.summary}>
{formatRatingSummary(students ?? { average: null, count: 0 }, {
Expand All @@ -71,13 +86,8 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) {
onDelete={handleDelete}
/>

{/* Always in the DOM, so screen readers announce the message when it changes. */}
<p role="status" className={styles.message}>
{message}
</p>

{reviews.length > 0 ? (
<ol className={styles.list}>
<ol className={styles.list} aria-labelledby="student-reviews-title">
{reviews.map((review) => (
<li key={review.id} className={styles.review}>
<Stars value={review.rating} size={18} />{' '}
Expand Down