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 .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,6 @@ jobs:

- name: Typecheck
run: pnpm typecheck

- name: Test
run: pnpm test
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ dist-ssr
__unconfig*
todos.json
**/src/generated/
test-results/
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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`
Expand Down
2 changes: 2 additions & 0 deletions apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -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",
Expand Down
29 changes: 29 additions & 0 deletions apps/backend/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -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,
},
}
: {}),
})
255 changes: 255 additions & 0 deletions apps/backend/tests/e2e/api.spec.ts
Original file line number Diff line number Diff line change
@@ -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<T> = {
data?: T | null
errors?: { message: string }[]
}

async function query<T>(
request: APIRequestContext,
document: string,
variables?: Record<string, unknown>,
): Promise<T> {
const response = await request.post('/', {
data: { query: document, variables },
})
const body: GraphQLResponse<T> = 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<unknown> = 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.',
)
})
2 changes: 1 addition & 1 deletion apps/backend/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"include": ["src"],
"include": ["src", "playwright.config.ts", "tests/e2e"],

"compilerOptions": {
"target": "ES2022",
Expand Down
10 changes: 9 additions & 1 deletion apps/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"generate-routes": "tsr generate",
"build": "vite build",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
Expand All @@ -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"
}
}
Loading