diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e73b206..11c837c 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -37,3 +37,6 @@ jobs: - name: Typecheck run: pnpm typecheck + + - name: Test + run: pnpm test diff --git a/.gitignore b/.gitignore index 104efb0..caea02b 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ dist-ssr __unconfig* todos.json **/src/generated/ +test-results/ diff --git a/README.md b/README.md index a690cdb..fd03ca1 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,8 @@ Frontend: http://localhost:3000 · GraphQL API: http://localhost:3001 | `pnpm build` | Build all workspaces that define a build | | `pnpm typecheck` | Typecheck all workspaces | | `pnpm lint` / `pnpm format` / `pnpm check` | Lint, auto-fix format, and check formatting | +| `pnpm test` | Run the frontend component tests once | +| `pnpm test:watch` | Re-run tests while developing | | `pnpm db:setup` | Provision PostgreSQL natively on Ubuntu (see below) | | `pnpm db:generate` | Regenerate the Prisma client and Pothos types | | `pnpm db:push` | Push the Prisma schema to the database (prototyping) | @@ -109,6 +111,21 @@ pnpm format # Runs the prettier formatter pnpm check # Runs the prettier formatter in check mode, so will not write to any files ``` +### Testing + +The frontend uses [Vitest](https://vitest.dev/) with [Testing Library](https://testing-library.com/docs/react-testing-library/intro/) and jsdom. Component tests live in `apps/frontend/src/components/__tests__`, and shared fixtures and providers are in `apps/frontend/src/test`. The tests cover rendering, user interaction, form validation, routing and the map wrappers without needing a running backend. + +```bash +pnpm test # Run all component tests once +pnpm test:watch # Re-run tests while developing +``` + +The backend API has Playwright end-to-end tests that send requests to the running GraphQL API. They require PostgreSQL, the backend `.env`, and the sample data created by `pnpm db:seed` (which replaces existing database rows). The test command starts the backend automatically; set `API_BASE_URL` to use an already-running API instead. + +```bash +pnpm test:e2e:backend +``` + ### Deployment The deployment of both the backend and frontend is automated using the github action found in `./.github/workflows/deploy-to-vm.yaml` diff --git a/apps/backend/package.json b/apps/backend/package.json index 35c9398..c44c870 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -5,6 +5,7 @@ "scripts": { "dev": "dotenv -e .env -- tsx watch src/index.ts", "start": "dotenv -e .env -- tsx src/index.ts", + "test:e2e": "dotenv -e .env -- playwright test", "typecheck": "tsc --noEmit" }, "dependencies": { @@ -16,6 +17,7 @@ "graphql": "^16.9.0" }, "devDependencies": { + "@playwright/test": "^1.64.1", "@types/node": "^22.20.4", "dotenv-cli": "^11.0.0", "tsx": "^4.23.15", diff --git a/apps/backend/playwright.config.ts b/apps/backend/playwright.config.ts new file mode 100644 index 0000000..ae30a41 --- /dev/null +++ b/apps/backend/playwright.config.ts @@ -0,0 +1,29 @@ +import { defineConfig } from '@playwright/test' +import { fileURLToPath } from 'node:url' + +const apiBaseURL = ( + process.env.API_BASE_URL ?? 'http://127.0.0.1:3001' +).replace(/\/+$/, '') +const managesLocalServer = process.env.API_BASE_URL === undefined + +export default defineConfig({ + testDir: './tests/e2e', + fullyParallel: true, + forbidOnly: Boolean(process.env.CI), + retries: process.env.CI ? 1 : 0, + reporter: 'list', + use: { + baseURL: apiBaseURL, + }, + ...(managesLocalServer + ? { + webServer: { + command: 'pnpm run start', + cwd: fileURLToPath(new URL('.', import.meta.url)), + url: `${apiBaseURL}/?query=%7B__typename%7D`, + reuseExistingServer: !process.env.CI, + timeout: 120_000, + }, + } + : {}), +}) diff --git a/apps/backend/tests/e2e/api.spec.ts b/apps/backend/tests/e2e/api.spec.ts new file mode 100644 index 0000000..9165e06 --- /dev/null +++ b/apps/backend/tests/e2e/api.spec.ts @@ -0,0 +1,255 @@ +import { expect, test } from '@playwright/test' +import type { APIRequestContext } from '@playwright/test' +import { randomUUID } from 'node:crypto' + +import { prisma } from '@t09-project-2/db' + +type GraphQLResponse = { + data?: T | null + errors?: { message: string }[] +} + +async function query( + request: APIRequestContext, + document: string, + variables?: Record, +): Promise { + const response = await request.post('/', { + data: { query: document, variables }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors).toBeUndefined() + + if (body.data == null) { + throw new Error('GraphQL response did not contain data') + } + + return body.data +} + +test('city query returns Trondheim and its map coordinates', async ({ + request, +}) => { + const { city } = await query<{ + city: { id: string; name: string; lat: number; lon: number }[] + }>( + request, + ` + query { + city(name: "Trondheim") { + id + name + lat + lon + } + } + `, + ) + + expect(city).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: expect.any(String), + name: 'Trondheim', + lat: expect.any(Number), + lon: expect.any(Number), + }), + ]), + ) +}) + +test('venue query returns its related city, hours, prices, and reviews', async ({ + request, +}) => { + const { venue } = await query<{ + venue: { + name: string + city: { name: string } + openingHours: { days: string[] }[] + pricesSighted: { price: number }[] + reviews: { username: string; rating: number }[] + }[] + }>( + request, + ` + query { + venue { + name + city { + name + } + openingHours { + days + } + pricesSighted { + price + } + reviews { + username + rating + } + } + } + `, + ) + + const seededVenue = venue.find(({ name }) => name === 'Den Gode Nabo') + expect(seededVenue).toBeDefined() + + if (!seededVenue) { + throw new Error('Seeded venue "Den Gode Nabo" was not returned') + } + + expect(seededVenue.city.name).toBe('Trondheim') + expect(seededVenue.openingHours).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + days: expect.arrayContaining(['MON']), + }), + ]), + ) + expect(seededVenue.pricesSighted.length).toBeGreaterThan(0) + expect(seededVenue.reviews.length).toBeGreaterThan(0) +}) + +test('createReview returns and persists a review for its venue', async ({ + request, +}) => { + const { venue } = await query<{ venue: { id: string; name: string }[] }>( + request, + ` + query { + venue { + id + name + } + } + `, + ) + const seededVenue = venue.find(({ name }) => name === 'Den Gode Nabo') + expect(seededVenue).toBeDefined() + + if (!seededVenue) { + throw new Error('Seeded venue "Den Gode Nabo" was not returned') + } + + const username = `playwright-${randomUUID()}` + const body = `E2E review ${randomUUID()}` + let createdReviewId: string | undefined + + try { + const { createReview } = await query<{ + createReview: { + id: string + username: string + body: string + rating: number + timeCreated: string + } + }>( + request, + ` + mutation CreateReview($input: MutationCreateReviewInput!) { + createReview(input: $input) { + id + username + body + rating + timeCreated + } + } + `, + { + input: { + venueId: seededVenue.id, + username, + body, + rating: 4, + }, + }, + ) + createdReviewId = createReview.id + + expect(createReview).toMatchObject({ + id: expect.any(String), + username, + body, + rating: 4, + }) + expect(Number.isNaN(Date.parse(createReview.timeCreated))).toBe(false) + + const { venue: venuesWithReviews } = await query<{ + venue: { + id: string + reviews: { + id: string + username: string + body: string + rating: number + venueId: string + }[] + }[] + }>( + request, + ` + query { + venue { + id + reviews { + id + username + body + rating + venueId + } + } + } + `, + ) + const persistedReview = venuesWithReviews + .find(({ id }) => id === seededVenue.id) + ?.reviews.find(({ id }) => id === createReview.id) + + expect(persistedReview).toEqual({ + id: createReview.id, + username, + body, + rating: 4, + venueId: seededVenue.id, + }) + } finally { + if (createdReviewId) { + await prisma.review.deleteMany({ where: { id: createdReviewId } }) + } + } +}) + +test('createReview rejects input missing a required field', async ({ + request, +}) => { + const response = await request.post('/', { + data: { + query: ` + mutation { + createReview( + input: { + venueId: "00000000-0000-0000-0000-000000000000" + username: "playwright" + rating: 4 + } + ) { + id + } + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(400) + expect(body.errors?.[0]?.message).toContain( + 'Field "MutationCreateReviewInput.body" of required type "String!" was not provided.', + ) +}) diff --git a/apps/backend/tsconfig.json b/apps/backend/tsconfig.json index b440846..d7286d9 100644 --- a/apps/backend/tsconfig.json +++ b/apps/backend/tsconfig.json @@ -1,5 +1,5 @@ { - "include": ["src"], + "include": ["src", "playwright.config.ts", "tests/e2e"], "compilerOptions": { "target": "ES2022", diff --git a/apps/frontend/package.json b/apps/frontend/package.json index 4171bf1..6edb098 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -10,6 +10,8 @@ "generate-routes": "tsr generate", "build": "vite build", "preview": "vite preview", + "test": "vitest run", + "test:watch": "vitest", "typecheck": "tsc --noEmit" }, "dependencies": { @@ -32,12 +34,18 @@ "@tailwindcss/typography": "^0.5.20", "@tanstack/devtools-vite": "latest", "@tanstack/router-cli": "^1.167.39", + "@testing-library/dom": "^10.4.2", + "@testing-library/jest-dom": "^7.0.1", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.8", "@types/leaflet": "^1.9.22", "@types/node": "^22.20.4", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "@vitejs/plugin-react": "^6.1.1", + "jsdom": "^30.1.3", "typescript": "^6.0.3", - "vite": "^8.3.1" + "vite": "^8.3.1", + "vitest": "^5.0.5" } } diff --git a/apps/frontend/src/components/__tests__/AddReviewDialog.test.tsx b/apps/frontend/src/components/__tests__/AddReviewDialog.test.tsx new file mode 100644 index 0000000..ae3d639 --- /dev/null +++ b/apps/frontend/src/components/__tests__/AddReviewDialog.test.tsx @@ -0,0 +1,183 @@ +import { fireEvent, screen, waitFor } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { graphqlFetch } from '#/graphql/client' +import { CREATE_REVIEW } from '#/graphql/venues' +import { makeReview } from '#/test/fixtures' +import { renderWithProviders } from '#/test/render' +import AddReviewDialog from '../AddReviewDialog' + +vi.mock('#/graphql/client', () => ({ + graphqlFetch: vi.fn(), +})) + +const mockGraphqlFetch = vi.mocked(graphqlFetch) +const USERNAME_STORAGE_KEY = 'g-spotter:review-username' + +async function openDialog() { + const utils = renderWithProviders( + , + ) + const { user } = utils + + await user.click(await screen.findByRole('button', { name: 'Add review' })) + + return { ...utils, dialog: screen.getByRole('dialog') } +} + +function submitForm(dialog: HTMLElement) { + const form = dialog.querySelector('form') + + if (!form) throw new Error('The review dialog has no form') + + fireEvent.submit(form) +} + +async function fillValidReview( + user: ReturnType['user'], +) { + await user.type(screen.getByLabelText('Your name'), 'Kari') + await user.type(screen.getByLabelText('Your review'), 'Great beer') + await user.click(screen.getByRole('radio', { name: '4 out of 5 stars' })) +} + +describe('AddReviewDialog', () => { + beforeEach(() => { + mockGraphqlFetch.mockReset() + }) + + it('opens the dialog and restores a previously used name', async () => { + window.localStorage.setItem(USERNAME_STORAGE_KEY, 'Ola') + + const { dialog } = await openDialog() + + expect( + screen.getByRole('heading', { name: 'Add a review' }), + ).toBeInTheDocument() + expect(dialog).toHaveAttribute('open') + expect(screen.getByLabelText('Your name')).toHaveValue('Ola') + expect( + screen.getByText('Share your thoughts about Studentersamfundet.'), + ).toBeInTheDocument() + }) + + it('requires a name', async () => { + const { dialog } = await openDialog() + + submitForm(dialog) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Please enter your name.', + ) + expect(screen.getByLabelText('Your name')).toHaveFocus() + }) + + it('requires a rating', async () => { + const { user, dialog } = await openDialog() + + await user.type(screen.getByLabelText('Your name'), 'Kari') + submitForm(dialog) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Please choose a rating.', + ) + }) + + it('requires a review body', async () => { + const { user, dialog } = await openDialog() + + await user.type(screen.getByLabelText('Your name'), 'Kari') + await user.click(screen.getByRole('radio', { name: '4 out of 5 stars' })) + submitForm(dialog) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Please write a short review.', + ) + }) + + it('submits a trimmed review, saves the name and closes the dialog', async () => { + mockGraphqlFetch.mockResolvedValue({ + createReview: makeReview({ + body: 'Great beer', + rating: 4, + username: 'Kari', + }), + }) + + const { user, dialog, queryClient } = await openDialog() + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') + + await user.type(screen.getByLabelText('Your name'), ' Kari ') + await user.type(screen.getByLabelText('Your review'), ' Great beer ') + await user.click(screen.getByRole('radio', { name: '4 out of 5 stars' })) + + submitForm(dialog) + + await waitFor(() => { + expect(mockGraphqlFetch).toHaveBeenCalledWith(CREATE_REVIEW, { + input: { + venueId: 'venue-1', + username: 'Kari', + body: 'Great beer', + rating: 4, + }, + }) + }) + + expect(window.localStorage.getItem(USERNAME_STORAGE_KEY)).toBe('Kari') + + await waitFor(() => { + expect(dialog).not.toHaveAttribute('open') + }) + + expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['venues'] }) + }) + + it('shows the pending state while the review is being posted', async () => { + let resolveRequest: (value: { + createReview: ReturnType + }) => void = () => {} + + mockGraphqlFetch.mockReturnValue( + new Promise((resolve) => { + resolveRequest = resolve + }), + ) + + const { user, dialog } = await openDialog() + await fillValidReview(user) + submitForm(dialog) + + expect( + await screen.findByRole('button', { name: 'Posting…' }), + ).toBeDisabled() + + resolveRequest({ createReview: makeReview() }) + + await waitFor(() => { + expect(dialog).not.toHaveAttribute('open') + }) + }) + + it('shows an error and keeps the dialog open when posting fails', async () => { + mockGraphqlFetch.mockRejectedValue(new Error('Request failed')) + + const { user, dialog } = await openDialog() + await fillValidReview(user) + submitForm(dialog) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Could not post your review. Please try again.', + ) + expect(dialog).toHaveAttribute('open') + expect(screen.getByRole('button', { name: 'Post review' })).toBeEnabled() + }) + + it('closes the dialog with the close button', async () => { + const { user, dialog } = await openDialog() + + await user.click(screen.getByRole('button', { name: 'Close dialog' })) + + expect(dialog).not.toHaveAttribute('open') + }) +}) diff --git a/apps/frontend/src/components/__tests__/Breadcrumbs.test.tsx b/apps/frontend/src/components/__tests__/Breadcrumbs.test.tsx new file mode 100644 index 0000000..f8b2d67 --- /dev/null +++ b/apps/frontend/src/components/__tests__/Breadcrumbs.test.tsx @@ -0,0 +1,52 @@ +import { screen, within } from '@testing-library/react' +import { describe, expect, it } from 'vitest' + +import Breadcrumbs from '../Breadcrumbs' +import { renderWithProviders } from '#/test/render' + +describe('Breadcrumbs', () => { + it('renders a link for items with a city and marks the last item as current', async () => { + renderWithProviders( + , + ) + + const navigation = await screen.findByRole('navigation', { + name: 'Breadcrumb', + }) + const items = within(navigation).getAllByRole('listitem') + + expect(items).toHaveLength(2) + expect( + within(items[0]).getByRole('link', { name: 'Trondheim' }), + ).toHaveAttribute('href', '/trondheim/venues') + expect(within(items[1]).getByText('Studentersamfundet')).toHaveAttribute( + 'aria-current', + 'page', + ) + }) + + it('does not mark an item without a city as current when it is not last', async () => { + renderWithProviders( + , + ) + + expect(await screen.findByText('Sentrum')).not.toHaveAttribute( + 'aria-current', + ) + expect(screen.getByText('Studentersamfundet')).toHaveAttribute( + 'aria-current', + 'page', + ) + }) +}) diff --git a/apps/frontend/src/components/__tests__/Footer.test.tsx b/apps/frontend/src/components/__tests__/Footer.test.tsx new file mode 100644 index 0000000..98099cc --- /dev/null +++ b/apps/frontend/src/components/__tests__/Footer.test.tsx @@ -0,0 +1,16 @@ +import { render, screen } from '@testing-library/react' +import { describe, expect, it } from 'vitest' + +import Footer from '../Footer' + +describe('Footer', () => { + it('renders the copyright notice with the current year', () => { + render(