From c417e7b49f5fbec045f3b8c98e04bbe7e3cc7d8e Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:31:55 +0100 Subject: [PATCH 01/48] test: e2e setup --- .github/workflows/playwright.yml | 27 +++++ .gitignore | 10 +- Backend/Server.ts | 19 +++- E2E/E2EConfig.ts | 11 ++ E2E/Fixtures.ts | 184 +++++++++++++++++++++++++++++++ E2E/Global-Setup.ts | 40 +++++++ E2E/helpers.ts | 45 ++++++++ package-lock.json | 46 ++++++++ package.json | 131 +++++++++++----------- playwright.config.ts | 96 ++++++++++++++++ 10 files changed, 538 insertions(+), 71 deletions(-) create mode 100644 .github/workflows/playwright.yml create mode 100644 E2E/E2EConfig.ts create mode 100644 E2E/Fixtures.ts create mode 100644 E2E/Global-Setup.ts create mode 100644 E2E/helpers.ts create mode 100644 playwright.config.ts diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml new file mode 100644 index 0000000..3eb1314 --- /dev/null +++ b/.github/workflows/playwright.yml @@ -0,0 +1,27 @@ +name: Playwright Tests +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] +jobs: + test: + timeout-minutes: 60 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + - name: Install dependencies + run: npm ci + - name: Install Playwright Browsers + run: npx playwright install --with-deps + - name: Run Playwright tests + run: npx playwright test + - uses: actions/upload-artifact@v4 + if: ${{ !cancelled() }} + with: + name: playwright-report + path: playwright-report/ + retention-days: 30 diff --git a/.gitignore b/.gitignore index d84ea4e..2d3445c 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,12 @@ Coverage/ #Env file .env -.env.development \ No newline at end of file +.env.development +.env.e2e + +# Playwright +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +/playwright/.auth/ diff --git a/Backend/Server.ts b/Backend/Server.ts index c83244a..c614089 100644 --- a/Backend/Server.ts +++ b/Backend/Server.ts @@ -4,13 +4,20 @@ import { typeDefs } from './Schema.ts' import { resolvers } from './resolvers/index.ts' const server = new ApolloServer({ typeDefs, resolvers }) + +const port = Number(process.env.PORT ?? 3001) + const { url } = await startStandaloneServer(server, { - listen: { host: process.env.HOST ?? '127.0.0.1', port: 3001 }, - context: async ({ req }) => ({ - token: req.headers.authorization?.replace(/^Bearer /, '') ?? null - }) + listen: { + host: process.env.HOST ?? '127.0.0.1', + port, + }, + context: async ({ req }) => ({ + token: req.headers.authorization?.replace(/^Bearer /, '') ?? null, + }), }) + console.log( - `Database: ${process.env.DB_USER}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}` + `Database: ${process.env.DB_USER}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}` ) -console.log(`GraphQL server ready at ${url}`) +console.log(`GraphQL server ready at ${url}`) \ No newline at end of file diff --git a/E2E/E2EConfig.ts b/E2E/E2EConfig.ts new file mode 100644 index 0000000..0ccf96b --- /dev/null +++ b/E2E/E2EConfig.ts @@ -0,0 +1,11 @@ +export const FRONTEND_URL = 'http://localhost:5173' +export const BACKEND_URL = 'http://localhost:3002/' + +// Same local Postgres as development, but a separate database +export const TestDB = { + DB_HOST: '127.0.0.1', + DB_PORT: '5432', + DB_NAME: 'gamestart_e2e', + DB_USER: 'e2etestuser', + DB_PASSWORD: 'e2etestpassword', +} \ No newline at end of file diff --git a/E2E/Fixtures.ts b/E2E/Fixtures.ts new file mode 100644 index 0000000..094c704 --- /dev/null +++ b/E2E/Fixtures.ts @@ -0,0 +1,184 @@ +import { test as base, expect } from '@playwright/test' +import { BACKEND_URL } from './E2EConfig' + +export type TestUser = { + id: number + token: string + username: string + email: string +} + +export type SecondUser = TestUser & { + friendId: string +} + +type Fixtures = { + user: TestUser + secondUser: SecondUser + seedWishlist: (userId: number, count: number) => Promise +} + +// GraphQL helper +async function graphql( + request: any, + query: string, + variables = {}, + token?: string +) { + const res = await request.post(BACKEND_URL, { + headers: token + ? { Authorization: `Bearer ${token}` } + : {}, + data: { query, variables }, + }) + + if (!res.ok) { + const body = await res.text() + throw new Error( + `Backend request failed: ${res.status}\nResponse: ${body}` + ) + } + + const json = await res.json() + + if (json.errors) { + throw new Error(json.errors[0].message) + } + + return json.data +} + +// Create a test user +async function createUser(request: any): Promise { + const stamp = + `${Date.now()}${Math.random().toString(36).slice(2, 6)}` + + const username = `e2e${stamp}` + const email = `e2e+${stamp}@example.com` + + const data = await graphql( + request, + ` + mutation($u: String!, $e: String!, $p: String!) { + signup(username: $u, email: $e, password: $p) { + id + email + username + token + } + } + `, + { + u: username, + e: email, + p: 'secret123', + } + ) + + return data.signup +} + +export const test = base.extend({ + + // Main test user + user: async ({ request, context }, use) => { + const user = await createUser(request) + + await context.addInitScript((u) => { + localStorage.setItem('GameStart:user', JSON.stringify(u)) + }, user) + + await use(user) + }, + + // Second test user, including their actual FriendID + secondUser: async ({ request }, use) => { + const createdUser = await createUser(request) + + const data = await graphql( + request, + ` + query($userId: Int!) { + myFriendId(userId: $userId) + } + `, + { + userId: createdUser.id, + }, + createdUser.token + ) + + const secondUser: SecondUser = { + ...createdUser, + friendId: String(data.myFriendId), + } + + await use(secondUser) + }, + + // Seed a wishlist through the API + seedWishlist: async ( + { request, user, secondUser }, + use + ) => { + const seedWishlist = async ( + userId: number, + count: number + ) => { + const targetUser = + user.id === userId ? user : + secondUser.id === userId ? secondUser : + null + + if (!targetUser) { + throw new Error(`Unknown test user ID: ${userId}`) + } + + // Fetch available games + const gamesData = await graphql( + request, + ` + query { + games { + id + } + } + `, + {}, + targetUser.token + ) + + const games = gamesData.games.slice(0, count) + + if (games.length < count) { + throw new Error( + `Requested ${count} games, but only found ${games.length}.` + ) + } + + for (const game of games) { + // TODO: Replace with your actual wishlist mutation. + await graphql( + request, + ` + mutation($userId: Int!, $gameId: Int!) { + addToWishlist( + userId: $userId, + gameId: $gameId + ) + } + `, + { + userId, + gameId: game.id, + }, + targetUser.token + ) + } + } + + await use(seedWishlist) + }, +}) + +export { expect } \ No newline at end of file diff --git a/E2E/Global-Setup.ts b/E2E/Global-Setup.ts new file mode 100644 index 0000000..004dfc0 --- /dev/null +++ b/E2E/Global-Setup.ts @@ -0,0 +1,40 @@ +import { execFileSync } from 'node:child_process' +import pg from 'pg' +import { TestDB } from './E2EConfig' + +export default async function globalSetup() { + const admin = new pg.Client({ + host: TestDB.DB_HOST, + port: Number(TestDB.DB_PORT), + user: process.env.PG_ADMIN_USER ?? 'postgres', + password: process.env.PG_ADMIN_PASSWORD, + database: 'postgres', +}) + +await admin.connect() + +try { + const { rowCount } = await admin.query( + 'SELECT 1 FROM pg_database WHERE datname = $1', + [TestDB.DB_NAME], + ) + + if (!rowCount) { + await admin.query(`CREATE DATABASE "${TestDB.DB_NAME}"`) + } +} finally { + await admin.end() +} + +const env = { ...process.env, ...TestDB } + +for (const script of [ + 'Database/CreateTables.ts', + 'Database/FillDb.ts', +]) { + execFileSync(process.execPath, [script], { + env, + stdio: 'inherit', + }) +} +} \ No newline at end of file diff --git a/E2E/helpers.ts b/E2E/helpers.ts new file mode 100644 index 0000000..66652bc --- /dev/null +++ b/E2E/helpers.ts @@ -0,0 +1,45 @@ +import { expect } from './fixtures' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ + +// Reusable helpers + +export async function openMainPage(page: any) { + await page.goto('/') + await expect(page).toHaveURL(MAIN_PAGE) +} + +export async function getSection(page: any, heading: string) { + return page.getByRole('heading', { name: heading }) + .locator('xpath=ancestor::section[1]') +} + +export async function testCarousel(page: any, heading: string) { + const section = await getSection(page, heading) + + const nextButton = section.getByRole('button', { + name: /next|right/i + }) + + const previousButton = section.getByRole('button', { + name: /previous|prev|left/i + }) + + await expect(nextButton).toBeVisible() + await expect(previousButton).toBeVisible() + + const initialContent = await section.innerText() + + await nextButton.click() + await expect(section).not.toHaveText(initialContent) + + await previousButton.click() + await expect(section).toContainText( + initialContent.split('\n')[0] + ) +} + +export async function goBackToMain(page: any) { + await page.goBack() + await expect(page).toHaveURL(MAIN_PAGE) +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 4c7199c..f466a6c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@playwright/test": "^1.65.0", "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", "@testing-library/user-event": "^14.6.7", @@ -1639,6 +1640,22 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@playwright/test": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.0.tgz", + "integrity": "sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.65.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@polka/url": { "version": "1.0.0-next.29", "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", @@ -5146,6 +5163,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz", + "integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", + "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", diff --git a/package.json b/package.json index 066c2a0..de42bdb 100644 --- a/package.json +++ b/package.json @@ -1,66 +1,69 @@ { - "name": "t10-project-2", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "tsc -b && vite build", - "lint": "eslint .", - "preview": "vite preview", - "format": "prettier --write \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", - "format:check": "prettier --check \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", - "test": "vitest", - "test:ui": "vitest --ui", - "test:coverage": "vitest run --coverage", - "server": "node Backend/Server.ts", - "db:create": "node Database/CreateTables.ts", - "db:fill": "node Database/FillDb.ts", - "db:fill:genres":"node Database/FillGenres.ts", - "server:local": "node --env-file=Frontend/.env.development Backend/Server.ts", - "db:create:local": "node --env-file=Frontend/.env.development Database/CreateTables.ts", - "db:fill:local": "node --env-file=Frontend/.env.development Database/FillDb.ts", - "db:fill:genres:local":"node --env-file=Frontend/.env.development Database/FillGenres.ts" - }, - "dependencies": { - "@apollo/server": "^5.5.1", - "@emotion/react": "^11.14.0", - "@emotion/styled": "^11.14.1", - "@material/card": "^14.0.0", - "@mui/material": "^9.4.0", - "@types/bcrypt": "^6.0.0", - "bcrypt": "^6.0.0", - "dotenv": "^18.0.7", - "graphql": "^16.14.2", - "lucide-react": "^1.48.0", - "pg": "^8.23.1", - "react": "^19.2.8", - "react-dom": "^19.2.8", - "react-router-dom": "^7.18.4" - }, - "devDependencies": { - "@eslint/js": "^10.0.1", - "@testing-library/jest-dom": "^7.0.1", - "@testing-library/react": "^16.3.3", - "@testing-library/user-event": "^14.6.7", - "@types/bcrypt": "^6.0.0", - "@types/node": "^24.13.3", - "@types/pg": "^8.23.1", - "@types/react": "^19.2.18", - "@types/react-dom": "^19.2.7", - "@vitejs/plugin-react": "^6.1.1", - "@vitest/coverage-v8": "^5.0.5", - "@vitest/ui": "^5.0.5", - "eslint": "^10.10.0", - "eslint-config-prettier": "^10.1.8", - "eslint-plugin-react-hooks": "^7.1.1", - "eslint-plugin-react-refresh": "^0.5.6", - "globals": "^17.12.0", - "jsdom": "^29.1.1", - "prettier": "^3.9.8", - "typescript": "~6.0.2", - "typescript-eslint": "^8.69.0", - "vite": "^8.3.0", - "vitest": "^5.0.5" - } + "name": "t10-project-2", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview", + "format": "prettier --write \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", + "format:check": "prettier --check \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", + "test": "vitest", + "test:ui": "vitest --ui", + "test:coverage": "vitest run --coverage", + "test:e2e": "playwright test", + "test:e2e:ui": "playwright test --ui", + "server": "node Backend/Server.ts", + "db:create": "node Database/CreateTables.ts", + "db:fill": "node Database/FillDb.ts", + "db:fill:genres": "node Database/FillGenres.ts", + "server:local": "node --env-file=Frontend/.env.development Backend/Server.ts", + "db:create:local": "node --env-file=Frontend/.env.development Database/CreateTables.ts", + "db:fill:local": "node --env-file=Frontend/.env.development Database/FillDb.ts", + "db:fill:genres:local": "node --env-file=Frontend/.env.development Database/FillGenres.ts" + }, + "dependencies": { + "@apollo/server": "^5.5.1", + "@emotion/react": "^11.14.0", + "@emotion/styled": "^11.14.1", + "@material/card": "^14.0.0", + "@mui/material": "^9.4.0", + "@types/bcrypt": "^6.0.0", + "bcrypt": "^6.0.0", + "dotenv": "^18.0.7", + "graphql": "^16.14.2", + "lucide-react": "^1.48.0", + "pg": "^8.23.1", + "react": "^19.2.8", + "react-dom": "^19.2.8", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@playwright/test": "^1.65.0", + "@testing-library/jest-dom": "^7.0.1", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.7", + "@types/bcrypt": "^6.0.0", + "@types/node": "^24.13.3", + "@types/pg": "^8.23.1", + "@types/react": "^19.2.18", + "@types/react-dom": "^19.2.7", + "@vitejs/plugin-react": "^6.1.1", + "@vitest/coverage-v8": "^5.0.5", + "@vitest/ui": "^5.0.5", + "eslint": "^10.10.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-react-hooks": "^7.1.1", + "eslint-plugin-react-refresh": "^0.5.6", + "globals": "^17.12.0", + "jsdom": "^29.1.1", + "prettier": "^3.9.8", + "typescript": "~6.0.2", + "typescript-eslint": "^8.69.0", + "vite": "^8.3.0", + "vitest": "^5.0.5" + } } diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..43e6f91 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,96 @@ +/// +import { defineConfig, devices } from '@playwright/test'; +import { TestDB, FRONTEND_URL, BACKEND_URL } from './E2E/E2EConfig'; + +/** + * Read environment variables from file. + * https://github.com/motdotla/dotenv + */ +// import dotenv from 'dotenv'; +// import path from 'path'; +// dotenv.config({ path: path.resolve(__dirname, '.env') }); + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './E2E', + globalSetup: './E2E/Global-Setup.ts', + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: 'html', + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('')`. */ + baseURL: FRONTEND_URL, + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: 'on-first-retry', + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + + { + name: 'firefox', + use: { ...devices['Desktop Firefox'] }, + }, + + { + name: 'webkit', + use: { ...devices['Desktop Safari'] }, + }, + + /* Test against mobile viewports. */ + // { + // name: 'Mobile Chrome', + // use: { ...devices['Pixel 5'] }, + // }, + // { + // name: 'Mobile Safari', + // use: { ...devices['iPhone 12'] }, + // }, + + /* Test against branded browsers. */ + // { + // name: 'Microsoft Edge', + // use: { ...devices['Desktop Edge'], channel: 'msedge' }, + // }, + // { + // name: 'Google Chrome', + // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, + // }, + ], + + /* Run your local dev server before starting the tests */ + webServer: [ + { + command: 'npm run server:local', + url: BACKEND_URL, + reuseExistingServer: !process.env.CI, + timeout: 60_000, + env: { + ...TestDB, + PORT: '3002', + }, + }, + { + command: 'npm run dev -- --port 5173 --strictPort', + url: FRONTEND_URL, + reuseExistingServer: !process.env.CI, + timeout: 60_000, + env: { VITE_BACKEND_URL: BACKEND_URL} + }, + ] +}); From 52b2383d5f61e431a15a0d2304b0c533fe82b40d Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:47:30 +0100 Subject: [PATCH 02/48] test: tests --- E2E/Auth.spec.ts | 48 ++++++++++++++ E2E/Friendpage.spec.ts | 74 +++++++++++++++++++++ E2E/Mainpage.spec.ts | 65 +++++++++++++++++++ E2E/MainpageToGamepage.spec.ts | 53 +++++++++++++++ E2E/Navigation.spec.ts | 42 ++++++++++++ E2E/Profilepage.spec.ts | 47 ++++++++++++++ E2E/Reviews.spec.ts | 65 +++++++++++++++++++ E2E/Searchpage.spec.ts | 114 +++++++++++++++++++++++++++++++++ E2E/Wishlist.spec.ts | 71 ++++++++++++++++++++ 9 files changed, 579 insertions(+) create mode 100644 E2E/Auth.spec.ts create mode 100644 E2E/Friendpage.spec.ts create mode 100644 E2E/Mainpage.spec.ts create mode 100644 E2E/MainpageToGamepage.spec.ts create mode 100644 E2E/Navigation.spec.ts create mode 100644 E2E/Profilepage.spec.ts create mode 100644 E2E/Reviews.spec.ts create mode 100644 E2E/Searchpage.spec.ts create mode 100644 E2E/Wishlist.spec.ts diff --git a/E2E/Auth.spec.ts b/E2E/Auth.spec.ts new file mode 100644 index 0000000..131cde8 --- /dev/null +++ b/E2E/Auth.spec.ts @@ -0,0 +1,48 @@ +import { test, expect } from '@playwright/test' + +test('sign up, sign out, and fail to sign in with a wrong password', async ({ page }) => { + const stamp = Date.now() + const email = `ui+${stamp}@example.com` + const username = `ui${stamp}` + const password = 'secret123' + + // Main page -> Sign in page + await page.goto('/') + await page.getByRole('link', { name: 'Sign In' }).click() + await expect(page).toHaveURL(/#\/SignIn/i) + await expect(page.getByRole('heading', { name: 'Sign in' })).toBeVisible() + + // Sign in page -> Sign up page + await page.getByRole('link', { name: 'Sign up' }).click() + await expect(page).toHaveURL(/#\/signup/i) + await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible() + + // Make an account + await page.getByLabel('Email').fill(email) + await page.getByLabel('Username').fill(username) + await page.getByLabel('Password', { exact: true }).fill(password) + await page.getByLabel('Re-enter Password').fill(password) + await page.getByRole('button', { name: 'Sign up' }).click() + + // Signed up users land on the main page and are signed in + await expect(page).toHaveURL(/#\/$/) + await expect(page.getByRole('heading', { name: /Welcome to GameStart/ })).toBeVisible() + await expect(page.getByRole('link', { name: 'Sign Out' })).toBeVisible() + + // Sign out + await page.getByRole('link', { name: 'Sign Out' }).click() + await expect(page).toHaveURL(/#\/$/) + await expect(page.getByRole('link', { name: 'Sign In' })).toBeVisible() + await expect(page.getByRole('link', { name: 'Sign Out' })).toHaveCount(0) + + // Sign in again, with the wrong password + await page.getByRole('link', { name: 'Sign In' }).click() + await page.getByLabel('Email').fill(email) + await page.getByLabel('Password').fill('wrongpass1') + await page.getByRole('button', { name: 'Sign in' }).click() + + // Stays on the sign in page and shows an error, still signed out + await expect(page.getByRole('alert')).toBeVisible() + await expect(page).toHaveURL(/#\/SignIn/i) + await expect(page.getByRole('link', { name: 'Sign Out' })).toHaveCount(0) +}) \ No newline at end of file diff --git a/E2E/Friendpage.spec.ts b/E2E/Friendpage.spec.ts new file mode 100644 index 0000000..57fe02a --- /dev/null +++ b/E2E/Friendpage.spec.ts @@ -0,0 +1,74 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const FRIEND_PAGE = /#\/FriendsPage$/ + +test.describe('FriendPage', () => { + test.beforeEach(async ({ page, secondUser, seedWishlist }) => { + // Ensure the second user has at least 6 wishlist games. + await seedWishlist(secondUser.id, 6) + + await openMainPage(page) + + await page.getByRole('link', { + name: /friends/i + }).click() + + await expect(page).toHaveURL(FRIEND_PAGE) + }) + + async function addFriend(page: import('@playwright/test').Page, friendId: string, username: string) { + const friendInput = page.getByRole('textbox', { + name: /friend id/i + }) + + await friendInput.fill(friendId) + + await page.getByRole('button', { + name: 'Add', + exact: true + }).click() + + // Adding a friend automatically selects them. + const friendSelector = page.getByPlaceholder('Look at a friend') + + await expect(friendSelector).toHaveValue(username) + + // Wait until their wishlist has loaded. + await expect(page.locator('.games-grid-wishlist')).toBeVisible() + } + + test('Add a friend', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId, secondUser.username) + + await expect( + page.getByPlaceholder('Look at a friend') + ).toHaveValue(secondUser.username) + + await expect(page.locator('.games-grid-wishlist')).toBeVisible() + }) + + test('Friend wishlist pagination', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId, secondUser.username) + + const wishlistGames = page.locator('.games-grid-wishlist > *') + + // Five games are displayed per page. + await expect(wishlistGames).toHaveCount(5) + + const firstPageGame = (await wishlistGames.first().innerText()).trim() + + const nextPage = page.getByRole('button', { + name: 'Go to page 2' + }) + + await expect(nextPage).toBeVisible() + await nextPage.click() + + await expect(wishlistGames).toHaveCount(1) + + const secondPageGame = (await wishlistGames.first().innerText()).trim() + + expect(secondPageGame).not.toBe(firstPageGame) + }) +}) diff --git a/E2E/Mainpage.spec.ts b/E2E/Mainpage.spec.ts new file mode 100644 index 0000000..692b871 --- /dev/null +++ b/E2E/Mainpage.spec.ts @@ -0,0 +1,65 @@ + +import { test, expect } from './fixtures' +import { openMainPage, testCarousel } from './helpers' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ +const SEARCH_PAGE = /#\/SearchPage$/ + +// MainPage carousels + +test.describe('MainPage - Carousels', () => { + test.beforeEach(async ({ page }) => { + await openMainPage(page) + }) + + test('Top 10 featured games - next and previous buttons', async ({ page }) => { + await testCarousel(page, 'Top 10 Featured Games') + }) + + test('Discounted games - next and previous buttons', async ({ page }) => { + await testCarousel(page, 'Discounted Games') + }) +}) + +// MainPage components + +test('Smoke test - navigate through MainPage components', async ({ page }) => { + await openMainPage(page) + + // Passive game card -> GamePage + const passiveGameCard = page.locator('a[href*="GamePage/"]').first() + + await expect(passiveGameCard).toBeVisible() + await passiveGameCard.click() + + await expect(page).toHaveURL(GAME_PAGE) + + // GamePage -> MainPage using back button + await page.getByRole('button', { + name: /back/i + }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + + // MainPage -> SearchPage + await page.getByRole('link', { + name: /browse our catalog/i + }).click() + + await expect(page).toHaveURL(SEARCH_PAGE) + + // SearchPage -> MainPage using back button + await page.getByRole('button', { + name: /back/i + }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + + // See the game -> GamePage + await page.getByRole('button', { + name: /see this game/i + }).first().click() + + await expect(page).toHaveURL(GAME_PAGE) +}) diff --git a/E2E/MainpageToGamepage.spec.ts b/E2E/MainpageToGamepage.spec.ts new file mode 100644 index 0000000..c93bd26 --- /dev/null +++ b/E2E/MainpageToGamepage.spec.ts @@ -0,0 +1,53 @@ +import { test, expect } from './fixtures' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ + +test('open the top game, go back, and toggle the wishlist button', async ({ page, user }) => { + expect(user.id).toBeGreaterThan(0) + + await page.goto('/') + + const topSection = page.locator('section').filter({ + has: page.getByRole('heading', { name: /top 3 games/i }) + }).first() + + await expect(topSection.getByText(/loading/i)).toHaveCount(0) + + const firstGameLink = topSection.getByRole('link').first() + + await expect(firstGameLink).toBeVisible() + + const gameName = (await firstGameLink.innerText()).split('\n')[0].trim() + const href = await firstGameLink.getAttribute('href') + + expect(href).toMatch(GAME_PAGE) + + await firstGameLink.click() + + await expect(page).toHaveURL(GAME_PAGE) + await expect(page.getByRole('heading', { name: gameName }).first()).toBeVisible() + + await page.goBack() + await expect(page).toHaveURL(MAIN_PAGE) + + await page.goForward() + await expect(page).toHaveURL(GAME_PAGE) + + const addButton = page.getByRole('button', { + name: /add to wishlist/i + }) + + const removeButton = page.getByRole('button', { + name: /remove from wishlist/i + }) + + await expect(addButton).toBeVisible() + await addButton.click() + + await expect(removeButton).toBeVisible() + + await removeButton.click() + + await expect(addButton).toBeVisible() +}) diff --git a/E2E/Navigation.spec.ts b/E2E/Navigation.spec.ts new file mode 100644 index 0000000..838e89e --- /dev/null +++ b/E2E/Navigation.spec.ts @@ -0,0 +1,42 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const SEARCH_PAGE = /#\/SearchPage$/ +const WISHLIST_PAGE = /#\/WishlistPage$/ +const FRIEND_PAGE = /#\/FriendsPage$/ +const PROFILE_PAGE = /#\/ProfilePage$/ +const SIGNIN_PAGE = /#\/SignInPage$/ +const SIGNUP_PAGE = /#\/SignUpPage$/ + +test('Smoke test - navigate through all header pages', async ({ page }) => { + await openMainPage(page) + + // MainPage -> SearchPage + await page.getByRole('link', { name: /browse games/i }).click() + await expect(page).toHaveURL(SEARCH_PAGE) + + // SearchPage -> WishlistPage + await page.getByRole('link', { name: /wishlist/i }).click() + await expect(page).toHaveURL(WISHLIST_PAGE) + + // WishlistPage -> FriendsPage + await page.getByRole('link', { name: /friends/i }).click() + await expect(page).toHaveURL(FRIEND_PAGE) + + // FriendsPage -> ProfilePage + await page.getByRole('link', { name: /profile/i }).click() + await expect(page).toHaveURL(PROFILE_PAGE) + + // ProfilePage -> SignInPage + await page.getByRole('link', { name: /sign out|logout/i }).click() + await expect(page).toHaveURL(SIGNIN_PAGE) + + // SignInPage -> SignUpPage + await page.getByRole('link', { name: /sign up|register/i }).click() + await expect(page).toHaveURL(SIGNUP_PAGE) + + // SignUpPage -> MainPage using logo + await page.getByRole('link', { name: /logo|home/i }).click() + await expect(page).toHaveURL(MAIN_PAGE) +}) diff --git a/E2E/Profilepage.spec.ts b/E2E/Profilepage.spec.ts new file mode 100644 index 0000000..09ecb1d --- /dev/null +++ b/E2E/Profilepage.spec.ts @@ -0,0 +1,47 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const PROFILE_PAGE = /#\/ProfilePage$/ + +test('ProfilePage - edit and save profile', async ({ page, user }) => { + expect(user.id).toBeGreaterThan(0) + + await openMainPage(page) + + await page.getByRole('link', { + name: /profile/i + }).click() + + await expect(page).toHaveURL(PROFILE_PAGE) + + await expect(page.getByRole('button', { + name: /edit profile/i + })).toBeVisible() + + await page.getByRole('button', { + name: /edit profile/i + }).click() + + const newDescription = `Automated profile test ${Date.now()}` + + // Adjust this locator to the actual label in ProfileEditor.tsx. + const descriptionInput = page.getByRole('textbox', { + name: /description/i + }) + + await descriptionInput.fill(newDescription) + + // Adjust this name if ProfileEditor uses a different save label. + await page.getByRole('button', { + name: /^save$/i + }).click() + + await expect(page.getByText(newDescription, { + exact: true + })).toBeVisible() + + // The editor should close after a successful save. + await expect(page.getByRole('button', { + name: /edit profile/i + })).toBeVisible() +}) diff --git a/E2E/Reviews.spec.ts b/E2E/Reviews.spec.ts new file mode 100644 index 0000000..64c7610 --- /dev/null +++ b/E2E/Reviews.spec.ts @@ -0,0 +1,65 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ + +test('MainPage - write a review and check Recent Reviews', async ({ page, user }) => { + expect(user.id).toBeGreaterThan(0) + + await openMainPage(page) + + const reviewsSection = page.locator('section.main-page-reviews') + + await expect(reviewsSection.getByRole('heading', { + name: /recent reviews/i + })).toBeVisible() + + await expect(reviewsSection.getByText('Loading reviews...')).toHaveCount(0) + + const seeGameButton = reviewsSection.getByRole('button', { + name: /see this game/i + }).first() + + await expect(seeGameButton).toBeVisible() + await seeGameButton.click() + + await expect(page).toHaveURL(GAME_PAGE) + + const writeReviewButton = page.getByRole('button', { + name: /write review/i + }) + + await expect(writeReviewButton).toBeVisible() + await writeReviewButton.click() + + const reviewText = `Automated test review ${Date.now()}` + + const reviewInput = page.getByRole('textbox', { + name: /review|comment/i + }) + + await reviewInput.fill(reviewText) + + const rating = page.getByRole('button', { + name: /5 stars|5 star/i + }) + + if (await rating.count()) { + await rating.click() + } + + await page.getByRole('button', { + name: /submit review|post review|save review/i + }).click() + + // Return to MainPage using the header logo. + await page.getByRole('link', { name: /logo|home/i }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + + const recentReviews = page.locator('section.main-page-reviews') + + await expect(recentReviews.getByText('Loading reviews...')).toHaveCount(0) + await expect(recentReviews).toContainText(reviewText) +}) diff --git a/E2E/Searchpage.spec.ts b/E2E/Searchpage.spec.ts new file mode 100644 index 0000000..1324c35 --- /dev/null +++ b/E2E/Searchpage.spec.ts @@ -0,0 +1,114 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const SEARCH_PAGE = /#\/SearchPage$/ + +test.describe('SearchPage', () => { + test.beforeEach(async ({ page }) => { + await openMainPage(page) + + await page.getByRole('link', { + name: /browse games/i, + }).click() + + await expect(page).toHaveURL(SEARCH_PAGE) + await expect(page.getByText('Loading games...')).toHaveCount(0) +}) + +test('Search for games', async ({ page }) => { + const searchInput = page.getByPlaceholder( + 'Search here or use filter' + ) + + await searchInput.fill('The Witcher') + await searchInput.press('Enter') + + await expect(page.getByText(/witcher/i).first()).toBeVisible() +}) + +test('Search with no matching results', async ({ page }) => { + const searchInput = page.getByPlaceholder( + 'Search here or use filter' + ) + + await searchInput.fill('rtrdfghriufhwe') + await searchInput.press('Enter') + + await expect(page.getByText('No games found.')).toBeVisible() +}) + +test('Filter games by genre', async ({ page }) => { + // Filters are hidden initially unless the filter menu is active. + await page.getByRole('button', { + name: 'Toggle filters', + }).click() + + const filter = page.getByRole('combobox', { + name: 'Filter by genre', + }) + + await expect(filter).toBeVisible() + await filter.click() + + const options = page.getByRole('option') + + await expect(options.first()).toBeVisible() + + const firstOption = options.first() + const genreName = (await firstOption.innerText()).trim() + + await firstOption.click() + + await expect(filter).toContainText(genreName) +}) + +test('Sort games', async ({ page }) => { + await page.getByRole('button', { + name: 'Toggle filters', + }).click() + + const sortDropdown = page.getByRole('combobox', { + name: 'Sort by', + }) + + await expect(sortDropdown).toBeVisible() + await sortDropdown.click() + + await page.getByRole('option', { + name: 'Title: Z to A', + }).click() + + await expect(sortDropdown).toContainText('Title: Z to A') +}) + +test('Pagination - navigate between pages', async ({ page }) => { + const gameCards = page.locator('.games-grid-searchpage > *') + + await expect(gameCards).toHaveCount(12) + + const firstPageFirstGame = (await gameCards.first().innerText()).trim() + + // The page has two pagination components. + const pagination = page.locator('.pageinationSearch') + const nextPage = pagination.getByRole('button', { + name: 'Go to page 2', + }) + + await expect(nextPage).toBeVisible() + await nextPage.click() + + await expect(gameCards.first()).toBeVisible() + + await expect(gameCards.first()).not.toContainText( + firstPageFirstGame + ) + + await pagination.getByRole('button', { + name: 'Go to page 1', + }).click() + + await expect(gameCards.first()).toContainText( + firstPageFirstGame + ) +}) +}) diff --git a/E2E/Wishlist.spec.ts b/E2E/Wishlist.spec.ts new file mode 100644 index 0000000..23fa944 --- /dev/null +++ b/E2E/Wishlist.spec.ts @@ -0,0 +1,71 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const WISHLIST_PAGE = /#\/WishlistPage$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ + +test.describe('WishlistPage', () => { + test.beforeEach(async ({ page, user, seedWishlist }) => { + await seedWishlist(user.id, 3) + + await openMainPage(page) + + await page.getByRole('link', { + name: /wishlist/i, + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) + await expect(page.getByText('Loading games...')).toHaveCount(0) + }) + + test('Open a wishlisted game and navigate back', async ({ page }) => { + const firstGame = page.locator('a[href*="GamePage"]').first() + + await expect(firstGame).toBeVisible() + await firstGame.click() + + await expect(page).toHaveURL(GAME_PAGE) + + await page.getByRole('button', { + name: /back/i, + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) + }) + + test('Sort wishlist games', async ({ page }) => { + const sortDropdown = page.getByRole('combobox', { + name: /sort by/i, + }) + + await expect(sortDropdown).toBeVisible() + + await sortDropdown.click() + + await page.getByRole('option', { + name: 'Price: low to high', + }).click() + + await expect(sortDropdown).toContainText('Price: low to high') + }) + + test('Remove a game from wishlist', async ({ page }) => { + const firstGame = page.locator('a[href*="GamePage"]').first() + + await expect(firstGame).toBeVisible() + + const gameName = (await firstGame.innerText()).trim() + + const removeButton = page.getByRole('button', { + name: /remove/i, + }).first() + + await expect(removeButton).toBeVisible() + await removeButton.click() + + await expect(page.getByText(gameName, { + exact: false, + })).toHaveCount(0) + }) +}) From c59d83149cc8c0d9d822cf4fe50d7a45d7273496 Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:55:55 +0100 Subject: [PATCH 03/48] fix: making tests almost run I need to rebase --- E2E/Global-Setup.ts | 117 ++++++++++++++++++++++++++++++++++--------- playwright.config.ts | 2 +- 2 files changed, 95 insertions(+), 24 deletions(-) diff --git a/E2E/Global-Setup.ts b/E2E/Global-Setup.ts index 004dfc0..f1f19ee 100644 --- a/E2E/Global-Setup.ts +++ b/E2E/Global-Setup.ts @@ -1,40 +1,111 @@ + +import 'dotenv/config' import { execFileSync } from 'node:child_process' import pg from 'pg' import { TestDB } from './E2EConfig' export default async function globalSetup() { + const adminPassword = process.env.PG_ADMIN_PASSWORD + + if (!adminPassword) { + throw new Error( + 'PG_ADMIN_PASSWORD is missing. Check your root .env file.' + ) + } + const admin = new pg.Client({ host: TestDB.DB_HOST, port: Number(TestDB.DB_PORT), user: process.env.PG_ADMIN_USER ?? 'postgres', - password: process.env.PG_ADMIN_PASSWORD, + password: adminPassword, database: 'postgres', -}) + }) -await admin.connect() + // Safely quote PostgreSQL identifiers and string literals. + const quoteIdentifier = (value: string) => + `"${value.replace(/"/g, '""')}"` -try { - const { rowCount } = await admin.query( - 'SELECT 1 FROM pg_database WHERE datname = $1', - [TestDB.DB_NAME], - ) + const quoteLiteral = (value: string) => + `'${value.replace(/'/g, "''")}'` - if (!rowCount) { - await admin.query(`CREATE DATABASE "${TestDB.DB_NAME}"`) - } -} finally { - await admin.end() -} + try { + await admin.connect() + + // Create or update the dedicated E2E database user. + const roleResult = await admin.query( + 'SELECT 1 FROM pg_roles WHERE rolname = $1', + [TestDB.DB_USER] + ) + + if (roleResult.rowCount === 0) { + await admin.query( + `CREATE ROLE ${quoteIdentifier(TestDB.DB_USER)} + LOGIN PASSWORD ${quoteLiteral(TestDB.DB_PASSWORD)}` + ) + } else { + await admin.query( + `ALTER ROLE ${quoteIdentifier(TestDB.DB_USER)} + WITH LOGIN PASSWORD ${quoteLiteral(TestDB.DB_PASSWORD)}` + ) + } + + // Check whether the E2E database exists. + const dbResult = await admin.query( + 'SELECT 1 FROM pg_database WHERE datname = $1', + [TestDB.DB_NAME] + ) + + // Create the E2E database with the test user as owner. + if (dbResult.rowCount === 0) { + await admin.query( + `CREATE DATABASE ${quoteIdentifier(TestDB.DB_NAME)} + OWNER ${quoteIdentifier(TestDB.DB_USER)}` + ) + } else { + await admin.query( + `ALTER DATABASE ${quoteIdentifier(TestDB.DB_NAME)} + OWNER TO ${quoteIdentifier(TestDB.DB_USER)}` + ) + } -const env = { ...process.env, ...TestDB } + } finally { + await admin.end() + } -for (const script of [ - 'Database/CreateTables.ts', - 'Database/FillDb.ts', -]) { - execFileSync(process.execPath, [script], { - env, - stdio: 'inherit', + // Verify that the E2E credentials work. + const testConnection = new pg.Client({ + host: TestDB.DB_HOST, + port: Number(TestDB.DB_PORT), + user: TestDB.DB_USER, + password: TestDB.DB_PASSWORD, + database: TestDB.DB_NAME, }) + + try { + await testConnection.connect() + console.log('E2E database connection successful.') + } finally { + await testConnection.end() + } + + // Run database setup scripts using ONLY E2E credentials. + const env = { + ...process.env, + ...TestDB, + } + + for (const script of [ + 'Database/CreateTables.ts', + 'Database/FillDb.ts', + 'Database/FillGenres.ts', + ]) { + console.log(`Running ${script}...`) + + execFileSync(process.execPath, [script], { + env, + stdio: 'inherit', + }) + } + + console.log('E2E database setup completed.') } -} \ No newline at end of file diff --git a/playwright.config.ts b/playwright.config.ts index 43e6f91..7f08736 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -78,7 +78,7 @@ export default defineConfig({ { command: 'npm run server:local', url: BACKEND_URL, - reuseExistingServer: !process.env.CI, + reuseExistingServer: false, timeout: 60_000, env: { ...TestDB, From 993266f38ece643eeede8771b872c0845facab6f Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:57:55 +0100 Subject: [PATCH 04/48] fix: remove .env.e2e --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2d3445c..c6c0abd 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,6 @@ Coverage/ #Env file .env .env.development -.env.e2e # Playwright /test-results/ From 44b56fdddf3141d8de5a22b198ea1efa65e1086b Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:31:55 +0100 Subject: [PATCH 05/48] test: e2e setup --- .github/workflows/playwright.yml | 27 +++++ .gitignore | 10 +- Backend/Server.ts | 19 +++- E2E/E2EConfig.ts | 11 ++ E2E/Fixtures.ts | 184 +++++++++++++++++++++++++++++++ E2E/Global-Setup.ts | 40 +++++++ E2E/helpers.ts | 45 ++++++++ package-lock.json | 46 ++++++++ package.json | 127 ++++++++++----------- playwright.config.ts | 96 ++++++++++++++++ 10 files changed, 536 insertions(+), 69 deletions(-) create mode 100644 .github/workflows/playwright.yml create mode 100644 E2E/E2EConfig.ts create mode 100644 E2E/Fixtures.ts create mode 100644 E2E/Global-Setup.ts create mode 100644 E2E/helpers.ts create mode 100644 playwright.config.ts diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml new file mode 100644 index 0000000..3eb1314 --- /dev/null +++ b/.github/workflows/playwright.yml @@ -0,0 +1,27 @@ +name: Playwright Tests +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] +jobs: + test: + timeout-minutes: 60 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + - name: Install dependencies + run: npm ci + - name: Install Playwright Browsers + run: npx playwright install --with-deps + - name: Run Playwright tests + run: npx playwright test + - uses: actions/upload-artifact@v4 + if: ${{ !cancelled() }} + with: + name: playwright-report + path: playwright-report/ + retention-days: 30 diff --git a/.gitignore b/.gitignore index d84ea4e..2d3445c 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,12 @@ Coverage/ #Env file .env -.env.development \ No newline at end of file +.env.development +.env.e2e + +# Playwright +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +/playwright/.auth/ diff --git a/Backend/Server.ts b/Backend/Server.ts index c83244a..c614089 100644 --- a/Backend/Server.ts +++ b/Backend/Server.ts @@ -4,13 +4,20 @@ import { typeDefs } from './Schema.ts' import { resolvers } from './resolvers/index.ts' const server = new ApolloServer({ typeDefs, resolvers }) + +const port = Number(process.env.PORT ?? 3001) + const { url } = await startStandaloneServer(server, { - listen: { host: process.env.HOST ?? '127.0.0.1', port: 3001 }, - context: async ({ req }) => ({ - token: req.headers.authorization?.replace(/^Bearer /, '') ?? null - }) + listen: { + host: process.env.HOST ?? '127.0.0.1', + port, + }, + context: async ({ req }) => ({ + token: req.headers.authorization?.replace(/^Bearer /, '') ?? null, + }), }) + console.log( - `Database: ${process.env.DB_USER}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}` + `Database: ${process.env.DB_USER}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}` ) -console.log(`GraphQL server ready at ${url}`) +console.log(`GraphQL server ready at ${url}`) \ No newline at end of file diff --git a/E2E/E2EConfig.ts b/E2E/E2EConfig.ts new file mode 100644 index 0000000..0ccf96b --- /dev/null +++ b/E2E/E2EConfig.ts @@ -0,0 +1,11 @@ +export const FRONTEND_URL = 'http://localhost:5173' +export const BACKEND_URL = 'http://localhost:3002/' + +// Same local Postgres as development, but a separate database +export const TestDB = { + DB_HOST: '127.0.0.1', + DB_PORT: '5432', + DB_NAME: 'gamestart_e2e', + DB_USER: 'e2etestuser', + DB_PASSWORD: 'e2etestpassword', +} \ No newline at end of file diff --git a/E2E/Fixtures.ts b/E2E/Fixtures.ts new file mode 100644 index 0000000..094c704 --- /dev/null +++ b/E2E/Fixtures.ts @@ -0,0 +1,184 @@ +import { test as base, expect } from '@playwright/test' +import { BACKEND_URL } from './E2EConfig' + +export type TestUser = { + id: number + token: string + username: string + email: string +} + +export type SecondUser = TestUser & { + friendId: string +} + +type Fixtures = { + user: TestUser + secondUser: SecondUser + seedWishlist: (userId: number, count: number) => Promise +} + +// GraphQL helper +async function graphql( + request: any, + query: string, + variables = {}, + token?: string +) { + const res = await request.post(BACKEND_URL, { + headers: token + ? { Authorization: `Bearer ${token}` } + : {}, + data: { query, variables }, + }) + + if (!res.ok) { + const body = await res.text() + throw new Error( + `Backend request failed: ${res.status}\nResponse: ${body}` + ) + } + + const json = await res.json() + + if (json.errors) { + throw new Error(json.errors[0].message) + } + + return json.data +} + +// Create a test user +async function createUser(request: any): Promise { + const stamp = + `${Date.now()}${Math.random().toString(36).slice(2, 6)}` + + const username = `e2e${stamp}` + const email = `e2e+${stamp}@example.com` + + const data = await graphql( + request, + ` + mutation($u: String!, $e: String!, $p: String!) { + signup(username: $u, email: $e, password: $p) { + id + email + username + token + } + } + `, + { + u: username, + e: email, + p: 'secret123', + } + ) + + return data.signup +} + +export const test = base.extend({ + + // Main test user + user: async ({ request, context }, use) => { + const user = await createUser(request) + + await context.addInitScript((u) => { + localStorage.setItem('GameStart:user', JSON.stringify(u)) + }, user) + + await use(user) + }, + + // Second test user, including their actual FriendID + secondUser: async ({ request }, use) => { + const createdUser = await createUser(request) + + const data = await graphql( + request, + ` + query($userId: Int!) { + myFriendId(userId: $userId) + } + `, + { + userId: createdUser.id, + }, + createdUser.token + ) + + const secondUser: SecondUser = { + ...createdUser, + friendId: String(data.myFriendId), + } + + await use(secondUser) + }, + + // Seed a wishlist through the API + seedWishlist: async ( + { request, user, secondUser }, + use + ) => { + const seedWishlist = async ( + userId: number, + count: number + ) => { + const targetUser = + user.id === userId ? user : + secondUser.id === userId ? secondUser : + null + + if (!targetUser) { + throw new Error(`Unknown test user ID: ${userId}`) + } + + // Fetch available games + const gamesData = await graphql( + request, + ` + query { + games { + id + } + } + `, + {}, + targetUser.token + ) + + const games = gamesData.games.slice(0, count) + + if (games.length < count) { + throw new Error( + `Requested ${count} games, but only found ${games.length}.` + ) + } + + for (const game of games) { + // TODO: Replace with your actual wishlist mutation. + await graphql( + request, + ` + mutation($userId: Int!, $gameId: Int!) { + addToWishlist( + userId: $userId, + gameId: $gameId + ) + } + `, + { + userId, + gameId: game.id, + }, + targetUser.token + ) + } + } + + await use(seedWishlist) + }, +}) + +export { expect } \ No newline at end of file diff --git a/E2E/Global-Setup.ts b/E2E/Global-Setup.ts new file mode 100644 index 0000000..004dfc0 --- /dev/null +++ b/E2E/Global-Setup.ts @@ -0,0 +1,40 @@ +import { execFileSync } from 'node:child_process' +import pg from 'pg' +import { TestDB } from './E2EConfig' + +export default async function globalSetup() { + const admin = new pg.Client({ + host: TestDB.DB_HOST, + port: Number(TestDB.DB_PORT), + user: process.env.PG_ADMIN_USER ?? 'postgres', + password: process.env.PG_ADMIN_PASSWORD, + database: 'postgres', +}) + +await admin.connect() + +try { + const { rowCount } = await admin.query( + 'SELECT 1 FROM pg_database WHERE datname = $1', + [TestDB.DB_NAME], + ) + + if (!rowCount) { + await admin.query(`CREATE DATABASE "${TestDB.DB_NAME}"`) + } +} finally { + await admin.end() +} + +const env = { ...process.env, ...TestDB } + +for (const script of [ + 'Database/CreateTables.ts', + 'Database/FillDb.ts', +]) { + execFileSync(process.execPath, [script], { + env, + stdio: 'inherit', + }) +} +} \ No newline at end of file diff --git a/E2E/helpers.ts b/E2E/helpers.ts new file mode 100644 index 0000000..66652bc --- /dev/null +++ b/E2E/helpers.ts @@ -0,0 +1,45 @@ +import { expect } from './fixtures' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ + +// Reusable helpers + +export async function openMainPage(page: any) { + await page.goto('/') + await expect(page).toHaveURL(MAIN_PAGE) +} + +export async function getSection(page: any, heading: string) { + return page.getByRole('heading', { name: heading }) + .locator('xpath=ancestor::section[1]') +} + +export async function testCarousel(page: any, heading: string) { + const section = await getSection(page, heading) + + const nextButton = section.getByRole('button', { + name: /next|right/i + }) + + const previousButton = section.getByRole('button', { + name: /previous|prev|left/i + }) + + await expect(nextButton).toBeVisible() + await expect(previousButton).toBeVisible() + + const initialContent = await section.innerText() + + await nextButton.click() + await expect(section).not.toHaveText(initialContent) + + await previousButton.click() + await expect(section).toContainText( + initialContent.split('\n')[0] + ) +} + +export async function goBackToMain(page: any) { + await page.goBack() + await expect(page).toHaveURL(MAIN_PAGE) +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 4c7199c..f466a6c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@playwright/test": "^1.65.0", "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", "@testing-library/user-event": "^14.6.7", @@ -1639,6 +1640,22 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@playwright/test": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.0.tgz", + "integrity": "sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.65.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@polka/url": { "version": "1.0.0-next.29", "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", @@ -5146,6 +5163,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz", + "integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", + "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", diff --git a/package.json b/package.json index 16d3e32..201fb9d 100644 --- a/package.json +++ b/package.json @@ -1,64 +1,67 @@ { - "name": "t10-project-2", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "tsc -b && vite build", - "lint": "eslint .", - "preview": "vite preview", - "format": "prettier --write \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", - "format:check": "prettier --check \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", - "test": "vitest", - "test:ui": "vitest --ui", - "test:coverage": "vitest run --coverage", - "server": "node Backend/Server.ts", - "db:create": "node Database/CreateTables.ts", - "db:fill": "node Database/FillDb.ts", - "server:local": "node --env-file=Frontend/.env.development Backend/Server.ts", - "db:create:local": "node --env-file=Frontend/.env.development Database/CreateTables.ts", - "db:fill:local": "node --env-file=Frontend/.env.development Database/FillDb.ts" - }, - "dependencies": { - "@apollo/server": "^5.5.1", - "@emotion/react": "^11.14.0", - "@emotion/styled": "^11.14.1", - "@material/card": "^14.0.0", - "@mui/material": "^9.4.0", - "@types/bcrypt": "^6.0.0", - "bcrypt": "^6.0.0", - "dotenv": "^18.0.7", - "graphql": "^16.14.2", - "lucide-react": "^1.48.0", - "pg": "^8.23.1", - "react": "^19.2.8", - "react-dom": "^19.2.8", - "react-router-dom": "^7.18.4" - }, - "devDependencies": { - "@eslint/js": "^10.0.1", - "@testing-library/jest-dom": "^7.0.1", - "@testing-library/react": "^16.3.3", - "@testing-library/user-event": "^14.6.7", - "@types/bcrypt": "^6.0.0", - "@types/node": "^24.13.3", - "@types/pg": "^8.23.1", - "@types/react": "^19.2.18", - "@types/react-dom": "^19.2.7", - "@vitejs/plugin-react": "^6.1.1", - "@vitest/coverage-v8": "^5.0.5", - "@vitest/ui": "^5.0.5", - "eslint": "^10.10.0", - "eslint-config-prettier": "^10.1.8", - "eslint-plugin-react-hooks": "^7.1.1", - "eslint-plugin-react-refresh": "^0.5.6", - "globals": "^17.12.0", - "jsdom": "^29.1.1", - "prettier": "^3.9.8", - "typescript": "~6.0.2", - "typescript-eslint": "^8.69.0", - "vite": "^8.3.0", - "vitest": "^5.0.5" - } + "name": "t10-project-2", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview", + "format": "prettier --write \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", + "format:check": "prettier --check \"Frontend/**/*.{ts,tsx,css,md}\" \"Backend/**/*.{ts,tsx,css,md}\" \"Database/**/*.{ts,tsx,css,md}\"", + "test": "vitest", + "test:ui": "vitest --ui", + "test:coverage": "vitest run --coverage", + "test:e2e": "playwright test", + "test:e2e:ui": "playwright test --ui", + "server": "node Backend/Server.ts", + "db:create": "node Database/CreateTables.ts", + "db:fill": "node Database/FillDb.ts", + "server:local": "node --env-file=Frontend/.env.development Backend/Server.ts", + "db:create:local": "node --env-file=Frontend/.env.development Database/CreateTables.ts", + "db:fill:local": "node --env-file=Frontend/.env.development Database/FillDb.ts", + }, + "dependencies": { + "@apollo/server": "^5.5.1", + "@emotion/react": "^11.14.0", + "@emotion/styled": "^11.14.1", + "@material/card": "^14.0.0", + "@mui/material": "^9.4.0", + "@types/bcrypt": "^6.0.0", + "bcrypt": "^6.0.0", + "dotenv": "^18.0.7", + "graphql": "^16.14.2", + "lucide-react": "^1.48.0", + "pg": "^8.23.1", + "react": "^19.2.8", + "react-dom": "^19.2.8", + "react-router-dom": "^7.18.4" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@playwright/test": "^1.65.0", + "@testing-library/jest-dom": "^7.0.1", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.7", + "@types/bcrypt": "^6.0.0", + "@types/node": "^24.13.3", + "@types/pg": "^8.23.1", + "@types/react": "^19.2.18", + "@types/react-dom": "^19.2.7", + "@vitejs/plugin-react": "^6.1.1", + "@vitest/coverage-v8": "^5.0.5", + "@vitest/ui": "^5.0.5", + "eslint": "^10.10.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-react-hooks": "^7.1.1", + "eslint-plugin-react-refresh": "^0.5.6", + "globals": "^17.12.0", + "jsdom": "^29.1.1", + "prettier": "^3.9.8", + "typescript": "~6.0.2", + "typescript-eslint": "^8.69.0", + "vite": "^8.3.0", + "vitest": "^5.0.5" + } } diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..43e6f91 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,96 @@ +/// +import { defineConfig, devices } from '@playwright/test'; +import { TestDB, FRONTEND_URL, BACKEND_URL } from './E2E/E2EConfig'; + +/** + * Read environment variables from file. + * https://github.com/motdotla/dotenv + */ +// import dotenv from 'dotenv'; +// import path from 'path'; +// dotenv.config({ path: path.resolve(__dirname, '.env') }); + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './E2E', + globalSetup: './E2E/Global-Setup.ts', + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: 'html', + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('')`. */ + baseURL: FRONTEND_URL, + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: 'on-first-retry', + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + + { + name: 'firefox', + use: { ...devices['Desktop Firefox'] }, + }, + + { + name: 'webkit', + use: { ...devices['Desktop Safari'] }, + }, + + /* Test against mobile viewports. */ + // { + // name: 'Mobile Chrome', + // use: { ...devices['Pixel 5'] }, + // }, + // { + // name: 'Mobile Safari', + // use: { ...devices['iPhone 12'] }, + // }, + + /* Test against branded browsers. */ + // { + // name: 'Microsoft Edge', + // use: { ...devices['Desktop Edge'], channel: 'msedge' }, + // }, + // { + // name: 'Google Chrome', + // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, + // }, + ], + + /* Run your local dev server before starting the tests */ + webServer: [ + { + command: 'npm run server:local', + url: BACKEND_URL, + reuseExistingServer: !process.env.CI, + timeout: 60_000, + env: { + ...TestDB, + PORT: '3002', + }, + }, + { + command: 'npm run dev -- --port 5173 --strictPort', + url: FRONTEND_URL, + reuseExistingServer: !process.env.CI, + timeout: 60_000, + env: { VITE_BACKEND_URL: BACKEND_URL} + }, + ] +}); From 022dc672257d28a52a5eca74b43853ad396184ef Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:47:30 +0100 Subject: [PATCH 06/48] test: tests --- E2E/Auth.spec.ts | 48 ++++++++++++++ E2E/Friendpage.spec.ts | 74 +++++++++++++++++++++ E2E/Mainpage.spec.ts | 65 +++++++++++++++++++ E2E/MainpageToGamepage.spec.ts | 53 +++++++++++++++ E2E/Navigation.spec.ts | 42 ++++++++++++ E2E/Profilepage.spec.ts | 47 ++++++++++++++ E2E/Reviews.spec.ts | 65 +++++++++++++++++++ E2E/Searchpage.spec.ts | 114 +++++++++++++++++++++++++++++++++ E2E/Wishlist.spec.ts | 71 ++++++++++++++++++++ 9 files changed, 579 insertions(+) create mode 100644 E2E/Auth.spec.ts create mode 100644 E2E/Friendpage.spec.ts create mode 100644 E2E/Mainpage.spec.ts create mode 100644 E2E/MainpageToGamepage.spec.ts create mode 100644 E2E/Navigation.spec.ts create mode 100644 E2E/Profilepage.spec.ts create mode 100644 E2E/Reviews.spec.ts create mode 100644 E2E/Searchpage.spec.ts create mode 100644 E2E/Wishlist.spec.ts diff --git a/E2E/Auth.spec.ts b/E2E/Auth.spec.ts new file mode 100644 index 0000000..131cde8 --- /dev/null +++ b/E2E/Auth.spec.ts @@ -0,0 +1,48 @@ +import { test, expect } from '@playwright/test' + +test('sign up, sign out, and fail to sign in with a wrong password', async ({ page }) => { + const stamp = Date.now() + const email = `ui+${stamp}@example.com` + const username = `ui${stamp}` + const password = 'secret123' + + // Main page -> Sign in page + await page.goto('/') + await page.getByRole('link', { name: 'Sign In' }).click() + await expect(page).toHaveURL(/#\/SignIn/i) + await expect(page.getByRole('heading', { name: 'Sign in' })).toBeVisible() + + // Sign in page -> Sign up page + await page.getByRole('link', { name: 'Sign up' }).click() + await expect(page).toHaveURL(/#\/signup/i) + await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible() + + // Make an account + await page.getByLabel('Email').fill(email) + await page.getByLabel('Username').fill(username) + await page.getByLabel('Password', { exact: true }).fill(password) + await page.getByLabel('Re-enter Password').fill(password) + await page.getByRole('button', { name: 'Sign up' }).click() + + // Signed up users land on the main page and are signed in + await expect(page).toHaveURL(/#\/$/) + await expect(page.getByRole('heading', { name: /Welcome to GameStart/ })).toBeVisible() + await expect(page.getByRole('link', { name: 'Sign Out' })).toBeVisible() + + // Sign out + await page.getByRole('link', { name: 'Sign Out' }).click() + await expect(page).toHaveURL(/#\/$/) + await expect(page.getByRole('link', { name: 'Sign In' })).toBeVisible() + await expect(page.getByRole('link', { name: 'Sign Out' })).toHaveCount(0) + + // Sign in again, with the wrong password + await page.getByRole('link', { name: 'Sign In' }).click() + await page.getByLabel('Email').fill(email) + await page.getByLabel('Password').fill('wrongpass1') + await page.getByRole('button', { name: 'Sign in' }).click() + + // Stays on the sign in page and shows an error, still signed out + await expect(page.getByRole('alert')).toBeVisible() + await expect(page).toHaveURL(/#\/SignIn/i) + await expect(page.getByRole('link', { name: 'Sign Out' })).toHaveCount(0) +}) \ No newline at end of file diff --git a/E2E/Friendpage.spec.ts b/E2E/Friendpage.spec.ts new file mode 100644 index 0000000..57fe02a --- /dev/null +++ b/E2E/Friendpage.spec.ts @@ -0,0 +1,74 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const FRIEND_PAGE = /#\/FriendsPage$/ + +test.describe('FriendPage', () => { + test.beforeEach(async ({ page, secondUser, seedWishlist }) => { + // Ensure the second user has at least 6 wishlist games. + await seedWishlist(secondUser.id, 6) + + await openMainPage(page) + + await page.getByRole('link', { + name: /friends/i + }).click() + + await expect(page).toHaveURL(FRIEND_PAGE) + }) + + async function addFriend(page: import('@playwright/test').Page, friendId: string, username: string) { + const friendInput = page.getByRole('textbox', { + name: /friend id/i + }) + + await friendInput.fill(friendId) + + await page.getByRole('button', { + name: 'Add', + exact: true + }).click() + + // Adding a friend automatically selects them. + const friendSelector = page.getByPlaceholder('Look at a friend') + + await expect(friendSelector).toHaveValue(username) + + // Wait until their wishlist has loaded. + await expect(page.locator('.games-grid-wishlist')).toBeVisible() + } + + test('Add a friend', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId, secondUser.username) + + await expect( + page.getByPlaceholder('Look at a friend') + ).toHaveValue(secondUser.username) + + await expect(page.locator('.games-grid-wishlist')).toBeVisible() + }) + + test('Friend wishlist pagination', async ({ page, secondUser }) => { + await addFriend(page, secondUser.friendId, secondUser.username) + + const wishlistGames = page.locator('.games-grid-wishlist > *') + + // Five games are displayed per page. + await expect(wishlistGames).toHaveCount(5) + + const firstPageGame = (await wishlistGames.first().innerText()).trim() + + const nextPage = page.getByRole('button', { + name: 'Go to page 2' + }) + + await expect(nextPage).toBeVisible() + await nextPage.click() + + await expect(wishlistGames).toHaveCount(1) + + const secondPageGame = (await wishlistGames.first().innerText()).trim() + + expect(secondPageGame).not.toBe(firstPageGame) + }) +}) diff --git a/E2E/Mainpage.spec.ts b/E2E/Mainpage.spec.ts new file mode 100644 index 0000000..692b871 --- /dev/null +++ b/E2E/Mainpage.spec.ts @@ -0,0 +1,65 @@ + +import { test, expect } from './fixtures' +import { openMainPage, testCarousel } from './helpers' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ +const SEARCH_PAGE = /#\/SearchPage$/ + +// MainPage carousels + +test.describe('MainPage - Carousels', () => { + test.beforeEach(async ({ page }) => { + await openMainPage(page) + }) + + test('Top 10 featured games - next and previous buttons', async ({ page }) => { + await testCarousel(page, 'Top 10 Featured Games') + }) + + test('Discounted games - next and previous buttons', async ({ page }) => { + await testCarousel(page, 'Discounted Games') + }) +}) + +// MainPage components + +test('Smoke test - navigate through MainPage components', async ({ page }) => { + await openMainPage(page) + + // Passive game card -> GamePage + const passiveGameCard = page.locator('a[href*="GamePage/"]').first() + + await expect(passiveGameCard).toBeVisible() + await passiveGameCard.click() + + await expect(page).toHaveURL(GAME_PAGE) + + // GamePage -> MainPage using back button + await page.getByRole('button', { + name: /back/i + }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + + // MainPage -> SearchPage + await page.getByRole('link', { + name: /browse our catalog/i + }).click() + + await expect(page).toHaveURL(SEARCH_PAGE) + + // SearchPage -> MainPage using back button + await page.getByRole('button', { + name: /back/i + }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + + // See the game -> GamePage + await page.getByRole('button', { + name: /see this game/i + }).first().click() + + await expect(page).toHaveURL(GAME_PAGE) +}) diff --git a/E2E/MainpageToGamepage.spec.ts b/E2E/MainpageToGamepage.spec.ts new file mode 100644 index 0000000..c93bd26 --- /dev/null +++ b/E2E/MainpageToGamepage.spec.ts @@ -0,0 +1,53 @@ +import { test, expect } from './fixtures' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ + +test('open the top game, go back, and toggle the wishlist button', async ({ page, user }) => { + expect(user.id).toBeGreaterThan(0) + + await page.goto('/') + + const topSection = page.locator('section').filter({ + has: page.getByRole('heading', { name: /top 3 games/i }) + }).first() + + await expect(topSection.getByText(/loading/i)).toHaveCount(0) + + const firstGameLink = topSection.getByRole('link').first() + + await expect(firstGameLink).toBeVisible() + + const gameName = (await firstGameLink.innerText()).split('\n')[0].trim() + const href = await firstGameLink.getAttribute('href') + + expect(href).toMatch(GAME_PAGE) + + await firstGameLink.click() + + await expect(page).toHaveURL(GAME_PAGE) + await expect(page.getByRole('heading', { name: gameName }).first()).toBeVisible() + + await page.goBack() + await expect(page).toHaveURL(MAIN_PAGE) + + await page.goForward() + await expect(page).toHaveURL(GAME_PAGE) + + const addButton = page.getByRole('button', { + name: /add to wishlist/i + }) + + const removeButton = page.getByRole('button', { + name: /remove from wishlist/i + }) + + await expect(addButton).toBeVisible() + await addButton.click() + + await expect(removeButton).toBeVisible() + + await removeButton.click() + + await expect(addButton).toBeVisible() +}) diff --git a/E2E/Navigation.spec.ts b/E2E/Navigation.spec.ts new file mode 100644 index 0000000..838e89e --- /dev/null +++ b/E2E/Navigation.spec.ts @@ -0,0 +1,42 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const SEARCH_PAGE = /#\/SearchPage$/ +const WISHLIST_PAGE = /#\/WishlistPage$/ +const FRIEND_PAGE = /#\/FriendsPage$/ +const PROFILE_PAGE = /#\/ProfilePage$/ +const SIGNIN_PAGE = /#\/SignInPage$/ +const SIGNUP_PAGE = /#\/SignUpPage$/ + +test('Smoke test - navigate through all header pages', async ({ page }) => { + await openMainPage(page) + + // MainPage -> SearchPage + await page.getByRole('link', { name: /browse games/i }).click() + await expect(page).toHaveURL(SEARCH_PAGE) + + // SearchPage -> WishlistPage + await page.getByRole('link', { name: /wishlist/i }).click() + await expect(page).toHaveURL(WISHLIST_PAGE) + + // WishlistPage -> FriendsPage + await page.getByRole('link', { name: /friends/i }).click() + await expect(page).toHaveURL(FRIEND_PAGE) + + // FriendsPage -> ProfilePage + await page.getByRole('link', { name: /profile/i }).click() + await expect(page).toHaveURL(PROFILE_PAGE) + + // ProfilePage -> SignInPage + await page.getByRole('link', { name: /sign out|logout/i }).click() + await expect(page).toHaveURL(SIGNIN_PAGE) + + // SignInPage -> SignUpPage + await page.getByRole('link', { name: /sign up|register/i }).click() + await expect(page).toHaveURL(SIGNUP_PAGE) + + // SignUpPage -> MainPage using logo + await page.getByRole('link', { name: /logo|home/i }).click() + await expect(page).toHaveURL(MAIN_PAGE) +}) diff --git a/E2E/Profilepage.spec.ts b/E2E/Profilepage.spec.ts new file mode 100644 index 0000000..09ecb1d --- /dev/null +++ b/E2E/Profilepage.spec.ts @@ -0,0 +1,47 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const PROFILE_PAGE = /#\/ProfilePage$/ + +test('ProfilePage - edit and save profile', async ({ page, user }) => { + expect(user.id).toBeGreaterThan(0) + + await openMainPage(page) + + await page.getByRole('link', { + name: /profile/i + }).click() + + await expect(page).toHaveURL(PROFILE_PAGE) + + await expect(page.getByRole('button', { + name: /edit profile/i + })).toBeVisible() + + await page.getByRole('button', { + name: /edit profile/i + }).click() + + const newDescription = `Automated profile test ${Date.now()}` + + // Adjust this locator to the actual label in ProfileEditor.tsx. + const descriptionInput = page.getByRole('textbox', { + name: /description/i + }) + + await descriptionInput.fill(newDescription) + + // Adjust this name if ProfileEditor uses a different save label. + await page.getByRole('button', { + name: /^save$/i + }).click() + + await expect(page.getByText(newDescription, { + exact: true + })).toBeVisible() + + // The editor should close after a successful save. + await expect(page.getByRole('button', { + name: /edit profile/i + })).toBeVisible() +}) diff --git a/E2E/Reviews.spec.ts b/E2E/Reviews.spec.ts new file mode 100644 index 0000000..64c7610 --- /dev/null +++ b/E2E/Reviews.spec.ts @@ -0,0 +1,65 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ + +test('MainPage - write a review and check Recent Reviews', async ({ page, user }) => { + expect(user.id).toBeGreaterThan(0) + + await openMainPage(page) + + const reviewsSection = page.locator('section.main-page-reviews') + + await expect(reviewsSection.getByRole('heading', { + name: /recent reviews/i + })).toBeVisible() + + await expect(reviewsSection.getByText('Loading reviews...')).toHaveCount(0) + + const seeGameButton = reviewsSection.getByRole('button', { + name: /see this game/i + }).first() + + await expect(seeGameButton).toBeVisible() + await seeGameButton.click() + + await expect(page).toHaveURL(GAME_PAGE) + + const writeReviewButton = page.getByRole('button', { + name: /write review/i + }) + + await expect(writeReviewButton).toBeVisible() + await writeReviewButton.click() + + const reviewText = `Automated test review ${Date.now()}` + + const reviewInput = page.getByRole('textbox', { + name: /review|comment/i + }) + + await reviewInput.fill(reviewText) + + const rating = page.getByRole('button', { + name: /5 stars|5 star/i + }) + + if (await rating.count()) { + await rating.click() + } + + await page.getByRole('button', { + name: /submit review|post review|save review/i + }).click() + + // Return to MainPage using the header logo. + await page.getByRole('link', { name: /logo|home/i }).click() + + await expect(page).toHaveURL(MAIN_PAGE) + + const recentReviews = page.locator('section.main-page-reviews') + + await expect(recentReviews.getByText('Loading reviews...')).toHaveCount(0) + await expect(recentReviews).toContainText(reviewText) +}) diff --git a/E2E/Searchpage.spec.ts b/E2E/Searchpage.spec.ts new file mode 100644 index 0000000..1324c35 --- /dev/null +++ b/E2E/Searchpage.spec.ts @@ -0,0 +1,114 @@ +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const SEARCH_PAGE = /#\/SearchPage$/ + +test.describe('SearchPage', () => { + test.beforeEach(async ({ page }) => { + await openMainPage(page) + + await page.getByRole('link', { + name: /browse games/i, + }).click() + + await expect(page).toHaveURL(SEARCH_PAGE) + await expect(page.getByText('Loading games...')).toHaveCount(0) +}) + +test('Search for games', async ({ page }) => { + const searchInput = page.getByPlaceholder( + 'Search here or use filter' + ) + + await searchInput.fill('The Witcher') + await searchInput.press('Enter') + + await expect(page.getByText(/witcher/i).first()).toBeVisible() +}) + +test('Search with no matching results', async ({ page }) => { + const searchInput = page.getByPlaceholder( + 'Search here or use filter' + ) + + await searchInput.fill('rtrdfghriufhwe') + await searchInput.press('Enter') + + await expect(page.getByText('No games found.')).toBeVisible() +}) + +test('Filter games by genre', async ({ page }) => { + // Filters are hidden initially unless the filter menu is active. + await page.getByRole('button', { + name: 'Toggle filters', + }).click() + + const filter = page.getByRole('combobox', { + name: 'Filter by genre', + }) + + await expect(filter).toBeVisible() + await filter.click() + + const options = page.getByRole('option') + + await expect(options.first()).toBeVisible() + + const firstOption = options.first() + const genreName = (await firstOption.innerText()).trim() + + await firstOption.click() + + await expect(filter).toContainText(genreName) +}) + +test('Sort games', async ({ page }) => { + await page.getByRole('button', { + name: 'Toggle filters', + }).click() + + const sortDropdown = page.getByRole('combobox', { + name: 'Sort by', + }) + + await expect(sortDropdown).toBeVisible() + await sortDropdown.click() + + await page.getByRole('option', { + name: 'Title: Z to A', + }).click() + + await expect(sortDropdown).toContainText('Title: Z to A') +}) + +test('Pagination - navigate between pages', async ({ page }) => { + const gameCards = page.locator('.games-grid-searchpage > *') + + await expect(gameCards).toHaveCount(12) + + const firstPageFirstGame = (await gameCards.first().innerText()).trim() + + // The page has two pagination components. + const pagination = page.locator('.pageinationSearch') + const nextPage = pagination.getByRole('button', { + name: 'Go to page 2', + }) + + await expect(nextPage).toBeVisible() + await nextPage.click() + + await expect(gameCards.first()).toBeVisible() + + await expect(gameCards.first()).not.toContainText( + firstPageFirstGame + ) + + await pagination.getByRole('button', { + name: 'Go to page 1', + }).click() + + await expect(gameCards.first()).toContainText( + firstPageFirstGame + ) +}) +}) diff --git a/E2E/Wishlist.spec.ts b/E2E/Wishlist.spec.ts new file mode 100644 index 0000000..23fa944 --- /dev/null +++ b/E2E/Wishlist.spec.ts @@ -0,0 +1,71 @@ + +import { test, expect } from './fixtures' +import { openMainPage } from './helpers' + +const WISHLIST_PAGE = /#\/WishlistPage$/ +const GAME_PAGE = /#\/GamePage\/\d+$/ + +test.describe('WishlistPage', () => { + test.beforeEach(async ({ page, user, seedWishlist }) => { + await seedWishlist(user.id, 3) + + await openMainPage(page) + + await page.getByRole('link', { + name: /wishlist/i, + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) + await expect(page.getByText('Loading games...')).toHaveCount(0) + }) + + test('Open a wishlisted game and navigate back', async ({ page }) => { + const firstGame = page.locator('a[href*="GamePage"]').first() + + await expect(firstGame).toBeVisible() + await firstGame.click() + + await expect(page).toHaveURL(GAME_PAGE) + + await page.getByRole('button', { + name: /back/i, + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) + }) + + test('Sort wishlist games', async ({ page }) => { + const sortDropdown = page.getByRole('combobox', { + name: /sort by/i, + }) + + await expect(sortDropdown).toBeVisible() + + await sortDropdown.click() + + await page.getByRole('option', { + name: 'Price: low to high', + }).click() + + await expect(sortDropdown).toContainText('Price: low to high') + }) + + test('Remove a game from wishlist', async ({ page }) => { + const firstGame = page.locator('a[href*="GamePage"]').first() + + await expect(firstGame).toBeVisible() + + const gameName = (await firstGame.innerText()).trim() + + const removeButton = page.getByRole('button', { + name: /remove/i, + }).first() + + await expect(removeButton).toBeVisible() + await removeButton.click() + + await expect(page.getByText(gameName, { + exact: false, + })).toHaveCount(0) + }) +}) From 882268afbe37ea257656b82440540d75733957bb Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:55:55 +0100 Subject: [PATCH 07/48] fix: making tests almost run I need to rebase --- E2E/Global-Setup.ts | 117 ++++++++++++++++++++++++++++++++++--------- playwright.config.ts | 2 +- 2 files changed, 95 insertions(+), 24 deletions(-) diff --git a/E2E/Global-Setup.ts b/E2E/Global-Setup.ts index 004dfc0..f1f19ee 100644 --- a/E2E/Global-Setup.ts +++ b/E2E/Global-Setup.ts @@ -1,40 +1,111 @@ + +import 'dotenv/config' import { execFileSync } from 'node:child_process' import pg from 'pg' import { TestDB } from './E2EConfig' export default async function globalSetup() { + const adminPassword = process.env.PG_ADMIN_PASSWORD + + if (!adminPassword) { + throw new Error( + 'PG_ADMIN_PASSWORD is missing. Check your root .env file.' + ) + } + const admin = new pg.Client({ host: TestDB.DB_HOST, port: Number(TestDB.DB_PORT), user: process.env.PG_ADMIN_USER ?? 'postgres', - password: process.env.PG_ADMIN_PASSWORD, + password: adminPassword, database: 'postgres', -}) + }) -await admin.connect() + // Safely quote PostgreSQL identifiers and string literals. + const quoteIdentifier = (value: string) => + `"${value.replace(/"/g, '""')}"` -try { - const { rowCount } = await admin.query( - 'SELECT 1 FROM pg_database WHERE datname = $1', - [TestDB.DB_NAME], - ) + const quoteLiteral = (value: string) => + `'${value.replace(/'/g, "''")}'` - if (!rowCount) { - await admin.query(`CREATE DATABASE "${TestDB.DB_NAME}"`) - } -} finally { - await admin.end() -} + try { + await admin.connect() + + // Create or update the dedicated E2E database user. + const roleResult = await admin.query( + 'SELECT 1 FROM pg_roles WHERE rolname = $1', + [TestDB.DB_USER] + ) + + if (roleResult.rowCount === 0) { + await admin.query( + `CREATE ROLE ${quoteIdentifier(TestDB.DB_USER)} + LOGIN PASSWORD ${quoteLiteral(TestDB.DB_PASSWORD)}` + ) + } else { + await admin.query( + `ALTER ROLE ${quoteIdentifier(TestDB.DB_USER)} + WITH LOGIN PASSWORD ${quoteLiteral(TestDB.DB_PASSWORD)}` + ) + } + + // Check whether the E2E database exists. + const dbResult = await admin.query( + 'SELECT 1 FROM pg_database WHERE datname = $1', + [TestDB.DB_NAME] + ) + + // Create the E2E database with the test user as owner. + if (dbResult.rowCount === 0) { + await admin.query( + `CREATE DATABASE ${quoteIdentifier(TestDB.DB_NAME)} + OWNER ${quoteIdentifier(TestDB.DB_USER)}` + ) + } else { + await admin.query( + `ALTER DATABASE ${quoteIdentifier(TestDB.DB_NAME)} + OWNER TO ${quoteIdentifier(TestDB.DB_USER)}` + ) + } -const env = { ...process.env, ...TestDB } + } finally { + await admin.end() + } -for (const script of [ - 'Database/CreateTables.ts', - 'Database/FillDb.ts', -]) { - execFileSync(process.execPath, [script], { - env, - stdio: 'inherit', + // Verify that the E2E credentials work. + const testConnection = new pg.Client({ + host: TestDB.DB_HOST, + port: Number(TestDB.DB_PORT), + user: TestDB.DB_USER, + password: TestDB.DB_PASSWORD, + database: TestDB.DB_NAME, }) + + try { + await testConnection.connect() + console.log('E2E database connection successful.') + } finally { + await testConnection.end() + } + + // Run database setup scripts using ONLY E2E credentials. + const env = { + ...process.env, + ...TestDB, + } + + for (const script of [ + 'Database/CreateTables.ts', + 'Database/FillDb.ts', + 'Database/FillGenres.ts', + ]) { + console.log(`Running ${script}...`) + + execFileSync(process.execPath, [script], { + env, + stdio: 'inherit', + }) + } + + console.log('E2E database setup completed.') } -} \ No newline at end of file diff --git a/playwright.config.ts b/playwright.config.ts index 43e6f91..7f08736 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -78,7 +78,7 @@ export default defineConfig({ { command: 'npm run server:local', url: BACKEND_URL, - reuseExistingServer: !process.env.CI, + reuseExistingServer: false, timeout: 60_000, env: { ...TestDB, From 17a4b0d8c25cc1eb5e32740a231b1ac093704362 Mon Sep 17 00:00:00 2001 From: carmennt Date: Mon, 9 Nov 2026 23:57:55 +0100 Subject: [PATCH 08/48] fix: remove .env.e2e --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2d3445c..c6c0abd 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,6 @@ Coverage/ #Env file .env .env.development -.env.e2e # Playwright /test-results/ From 07300998aa5241dfec6f30d471080e2011d10608 Mon Sep 17 00:00:00 2001 From: carmennt Date: Tue, 10 Nov 2026 00:31:58 +0100 Subject: [PATCH 09/48] test: matching test to actual pages --- E2E/Fixtures.ts | 2 +- E2E/Global-Setup.ts | 1 - E2E/Mainpage.spec.ts | 16 +++++++--- E2E/MainpageToGamepage.spec.ts | 2 +- E2E/Navigation.spec.ts | 10 +++---- E2E/Profilepage.spec.ts | 52 +++++++++++--------------------- E2E/Reviews.spec.ts | 8 ++--- E2E/Searchpage.spec.ts | 54 ++++++++++++++++------------------ E2E/Wishlist.spec.ts | 6 ++-- package.json | 2 +- 10 files changed, 70 insertions(+), 83 deletions(-) diff --git a/E2E/Fixtures.ts b/E2E/Fixtures.ts index 094c704..f47a549 100644 --- a/E2E/Fixtures.ts +++ b/E2E/Fixtures.ts @@ -140,7 +140,7 @@ export const test = base.extend({ ` query { games { - id + appid } } `, diff --git a/E2E/Global-Setup.ts b/E2E/Global-Setup.ts index f1f19ee..af4b075 100644 --- a/E2E/Global-Setup.ts +++ b/E2E/Global-Setup.ts @@ -97,7 +97,6 @@ export default async function globalSetup() { for (const script of [ 'Database/CreateTables.ts', 'Database/FillDb.ts', - 'Database/FillGenres.ts', ]) { console.log(`Running ${script}...`) diff --git a/E2E/Mainpage.spec.ts b/E2E/Mainpage.spec.ts index 692b871..2550bdb 100644 --- a/E2E/Mainpage.spec.ts +++ b/E2E/Mainpage.spec.ts @@ -3,7 +3,7 @@ import { test, expect } from './fixtures' import { openMainPage, testCarousel } from './helpers' const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ -const GAME_PAGE = /#\/GamePage\/\d+$/ +const GAME_PAGE = /#\/gamepage\/\d+$/ const SEARCH_PAGE = /#\/SearchPage$/ // MainPage carousels @@ -13,8 +13,16 @@ test.describe('MainPage - Carousels', () => { await openMainPage(page) }) - test('Top 10 featured games - next and previous buttons', async ({ page }) => { - await testCarousel(page, 'Top 10 Featured Games') + test('Top 3 featured games are displayed', async ({ page }) => { + const section = page + .getByRole('heading', { name: 'Top 3 Games' }) + .locator('xpath=ancestor::section[1]') + + await expect(section).toBeVisible() + + await expect( + section.locator('.featured-game-card') + ).toHaveCount(3) }) test('Discounted games - next and previous buttons', async ({ page }) => { @@ -28,7 +36,7 @@ test('Smoke test - navigate through MainPage components', async ({ page }) => { await openMainPage(page) // Passive game card -> GamePage - const passiveGameCard = page.locator('a[href*="GamePage/"]').first() + const passiveGameCard = page.locator('a[href*="gamepage/"]').first() await expect(passiveGameCard).toBeVisible() await passiveGameCard.click() diff --git a/E2E/MainpageToGamepage.spec.ts b/E2E/MainpageToGamepage.spec.ts index c93bd26..fc9613c 100644 --- a/E2E/MainpageToGamepage.spec.ts +++ b/E2E/MainpageToGamepage.spec.ts @@ -1,7 +1,7 @@ import { test, expect } from './fixtures' const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ -const GAME_PAGE = /#\/GamePage\/\d+$/ +const GAME_PAGE = /#\/gamepage\/\d+$/ test('open the top game, go back, and toggle the wishlist button', async ({ page, user }) => { expect(user.id).toBeGreaterThan(0) diff --git a/E2E/Navigation.spec.ts b/E2E/Navigation.spec.ts index 838e89e..5fb9c04 100644 --- a/E2E/Navigation.spec.ts +++ b/E2E/Navigation.spec.ts @@ -17,23 +17,23 @@ test('Smoke test - navigate through all header pages', async ({ page }) => { await expect(page).toHaveURL(SEARCH_PAGE) // SearchPage -> WishlistPage - await page.getByRole('link', { name: /wishlist/i }).click() + await page.getByRole('link', { name: 'Wishlist', exact: true }).click() await expect(page).toHaveURL(WISHLIST_PAGE) // WishlistPage -> FriendsPage - await page.getByRole('link', { name: /friends/i }).click() + await page.getByRole('link', { name: 'Friends', exact: true }).click() await expect(page).toHaveURL(FRIEND_PAGE) // FriendsPage -> ProfilePage - await page.getByRole('link', { name: /profile/i }).click() + await page.getByRole('link', { name: 'Profile', exact: true }).click() await expect(page).toHaveURL(PROFILE_PAGE) // ProfilePage -> SignInPage - await page.getByRole('link', { name: /sign out|logout/i }).click() + await page.getByRole('link', { name: /SignIn|logout/i }).click() await expect(page).toHaveURL(SIGNIN_PAGE) // SignInPage -> SignUpPage - await page.getByRole('link', { name: /sign up|register/i }).click() + await page.getByRole('link', { name: /SignUp|register/i }).click() await expect(page).toHaveURL(SIGNUP_PAGE) // SignUpPage -> MainPage using logo diff --git a/E2E/Profilepage.spec.ts b/E2E/Profilepage.spec.ts index 09ecb1d..92beb0c 100644 --- a/E2E/Profilepage.spec.ts +++ b/E2E/Profilepage.spec.ts @@ -1,47 +1,29 @@ import { test, expect } from './fixtures' -import { openMainPage } from './helpers' -const PROFILE_PAGE = /#\/ProfilePage$/ - -test('ProfilePage - edit and save profile', async ({ page, user }) => { - expect(user.id).toBeGreaterThan(0) - - await openMainPage(page) - - await page.getByRole('link', { - name: /profile/i - }).click() - - await expect(page).toHaveURL(PROFILE_PAGE) - - await expect(page.getByRole('button', { - name: /edit profile/i - })).toBeVisible() +test('User can edit their profile', async ({ page }) => { + await page.goto('/#/ProfilePage') + // Open profile editor await page.getByRole('button', { - name: /edit profile/i + name: 'Edit profile', + exact: true, }).click() - const newDescription = `Automated profile test ${Date.now()}` + // Change description + const newDescription = 'This is my updated profile description.' - // Adjust this locator to the actual label in ProfileEditor.tsx. - const descriptionInput = page.getByRole('textbox', { - name: /description/i - }) + await page.getByRole('textbox', { + name: 'Description', + }).fill(newDescription) - await descriptionInput.fill(newDescription) - - // Adjust this name if ProfileEditor uses a different save label. + // Save profile await page.getByRole('button', { - name: /^save$/i + name: 'Save profile', + exact: true, }).click() - await expect(page.getByText(newDescription, { - exact: true - })).toBeVisible() - - // The editor should close after a successful save. - await expect(page.getByRole('button', { - name: /edit profile/i - })).toBeVisible() + // Verify updated description + await expect( + page.getByText(newDescription, { exact: true }) + ).toBeVisible() }) diff --git a/E2E/Reviews.spec.ts b/E2E/Reviews.spec.ts index 64c7610..31b26e9 100644 --- a/E2E/Reviews.spec.ts +++ b/E2E/Reviews.spec.ts @@ -2,7 +2,7 @@ import { test, expect } from './fixtures' import { openMainPage } from './helpers' const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ -const GAME_PAGE = /#\/GamePage\/\d+$/ +const GAME_PAGE = /#\/gamepage\/\d+$/ test('MainPage - write a review and check Recent Reviews', async ({ page, user }) => { expect(user.id).toBeGreaterThan(0) @@ -17,12 +17,12 @@ test('MainPage - write a review and check Recent Reviews', async ({ page, user } await expect(reviewsSection.getByText('Loading reviews...')).toHaveCount(0) - const seeGameButton = reviewsSection.getByRole('button', { + const seeGameLink = reviewsSection.getByRole('link', { name: /see this game/i }).first() - await expect(seeGameButton).toBeVisible() - await seeGameButton.click() + await expect(seeGameLink).toBeVisible() + await seeGameLink.click() await expect(page).toHaveURL(GAME_PAGE) diff --git a/E2E/Searchpage.spec.ts b/E2E/Searchpage.spec.ts index 1324c35..1ac45d4 100644 --- a/E2E/Searchpage.spec.ts +++ b/E2E/Searchpage.spec.ts @@ -37,21 +37,20 @@ test('Search with no matching results', async ({ page }) => { await expect(page.getByText('No games found.')).toBeVisible() }) + test('Filter games by genre', async ({ page }) => { - // Filters are hidden initially unless the filter menu is active. await page.getByRole('button', { - name: 'Toggle filters', + name: 'Toggle filters', }).click() const filter = page.getByRole('combobox', { - name: 'Filter by genre', + name: 'Filter by genre', }) await expect(filter).toBeVisible() await filter.click() const options = page.getByRole('option') - await expect(options.first()).toBeVisible() const firstOption = options.first() @@ -59,56 +58,55 @@ test('Filter games by genre', async ({ page }) => { await firstOption.click() + // MUI multiple Select displays the selected genre. await expect(filter).toContainText(genreName) + + // Wait for the filtered game results to finish loading. + await expect(page.getByText('Loading games...')).toHaveCount(0) }) test('Sort games', async ({ page }) => { await page.getByRole('button', { - name: 'Toggle filters', + name: 'Toggle filters', }).click() const sortDropdown = page.getByRole('combobox', { - name: 'Sort by', + name: 'Sort by', }) await expect(sortDropdown).toBeVisible() await sortDropdown.click() await page.getByRole('option', { - name: 'Title: Z to A', + name: 'Title: Z to A', }).click() await expect(sortDropdown).toContainText('Title: Z to A') + + await expect(page.getByText('Loading games...')).toHaveCount(0) }) -test('Pagination - navigate between pages', async ({ page }) => { +test('User can navigate between pages of search results', async ({ page }) => { const gameCards = page.locator('.games-grid-searchpage > *') await expect(gameCards).toHaveCount(12) - const firstPageFirstGame = (await gameCards.first().innerText()).trim() - - // The page has two pagination components. - const pagination = page.locator('.pageinationSearch') - const nextPage = pagination.getByRole('button', { - name: 'Go to page 2', - }) + // Store the first game's actual displayed text on page 1 + const firstPageFirstGame = await gameCards.first().innerText() - await expect(nextPage).toBeVisible() - await nextPage.click() + await page.getByRole('button', { name: 'Go to page 2' }).click() - await expect(gameCards.first()).toBeVisible() + await expect(gameCards).toHaveCount(12) - await expect(gameCards.first()).not.toContainText( - firstPageFirstGame - ) + // Wait until the first game changes + await expect(async () => { + const secondPageFirstGame = await gameCards.first().innerText() + expect(secondPageFirstGame).not.toBe(firstPageFirstGame) + }).toPass() - await pagination.getByRole('button', { - name: 'Go to page 1', - }).click() + await page.getByRole('button', { name: 'Go to page 1' }).click() - await expect(gameCards.first()).toContainText( - firstPageFirstGame - ) -}) + // Verify that page 1 is restored + await expect(gameCards.first()).toHaveText(firstPageFirstGame) + }) }) diff --git a/E2E/Wishlist.spec.ts b/E2E/Wishlist.spec.ts index 23fa944..980f43e 100644 --- a/E2E/Wishlist.spec.ts +++ b/E2E/Wishlist.spec.ts @@ -3,7 +3,7 @@ import { test, expect } from './fixtures' import { openMainPage } from './helpers' const WISHLIST_PAGE = /#\/WishlistPage$/ -const GAME_PAGE = /#\/GamePage\/\d+$/ +const GAME_PAGE = /#\/gamepage\/\d+$/ test.describe('WishlistPage', () => { test.beforeEach(async ({ page, user, seedWishlist }) => { @@ -20,7 +20,7 @@ test.describe('WishlistPage', () => { }) test('Open a wishlisted game and navigate back', async ({ page }) => { - const firstGame = page.locator('a[href*="GamePage"]').first() + const firstGame = page.locator('a[href*="gamepage"]').first() await expect(firstGame).toBeVisible() await firstGame.click() @@ -51,7 +51,7 @@ test.describe('WishlistPage', () => { }) test('Remove a game from wishlist', async ({ page }) => { - const firstGame = page.locator('a[href*="GamePage"]').first() + const firstGame = page.locator('a[href*="gamepage"]').first() await expect(firstGame).toBeVisible() diff --git a/package.json b/package.json index 201fb9d..b1cdbc4 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "db:fill": "node Database/FillDb.ts", "server:local": "node --env-file=Frontend/.env.development Backend/Server.ts", "db:create:local": "node --env-file=Frontend/.env.development Database/CreateTables.ts", - "db:fill:local": "node --env-file=Frontend/.env.development Database/FillDb.ts", + "db:fill:local": "node --env-file=Frontend/.env.development Database/FillDb.ts" }, "dependencies": { "@apollo/server": "^5.5.1", From faabf4c4a67883e1b5e33a736996ce7e7ad217ff Mon Sep 17 00:00:00 2001 From: carmennt Date: Tue, 10 Nov 2026 01:56:09 +0100 Subject: [PATCH 10/48] test: Tests run like they should --- E2E/Fixtures.ts | 154 +++++++++++++++++++----------- E2E/Friendpage.spec.ts | 36 ++++--- E2E/Mainpage.spec.ts | 52 +++------- E2E/MainpageToGamepage.spec.ts | 32 ++++--- E2E/Navigation.spec.ts | 25 ++--- E2E/Profilepage.spec.ts | 49 ++++++---- E2E/Reviews.spec.ts | 60 +++--------- E2E/Searchpage.spec.ts | 64 ++++++++----- E2E/Wishlist.spec.ts | 3 +- E2E/helpers.ts | 64 +++++++++---- Frontend/src/pages/SearchPage.tsx | 1 + 11 files changed, 290 insertions(+), 250 deletions(-) diff --git a/E2E/Fixtures.ts b/E2E/Fixtures.ts index f47a549..69dbfb5 100644 --- a/E2E/Fixtures.ts +++ b/E2E/Fixtures.ts @@ -16,6 +16,7 @@ type Fixtures = { user: TestUser secondUser: SecondUser seedWishlist: (userId: number, count: number) => Promise + seedReview: (userId: number) => Promise } // GraphQL helper @@ -117,68 +118,111 @@ export const test = base.extend({ }, // Seed a wishlist through the API - seedWishlist: async ( - { request, user, secondUser }, - use - ) => { - const seedWishlist = async ( - userId: number, - count: number - ) => { - const targetUser = - user.id === userId ? user : - secondUser.id === userId ? secondUser : - null - - if (!targetUser) { - throw new Error(`Unknown test user ID: ${userId}`) + seedWishlist: async ({ request, user, secondUser }, use) => { + const seedWishlist = async (userId: number, count: number) => { + const targetUser = + user.id === userId + ? user + : secondUser.id === userId + ? secondUser + : null + + if (!targetUser) { + throw new Error(`Unknown test user ID: ${userId}`) + } + + const gamesData = await graphql( + request, + ` + query { + games(limit: 500, offset: 0) { + appid } + } + `, + {}, + targetUser.token + ) - // Fetch available games - const gamesData = await graphql( - request, - ` - query { - games { - appid - } - } - `, - {}, - targetUser.token - ) - - const games = gamesData.games.slice(0, count) - - if (games.length < count) { - throw new Error( - `Requested ${count} games, but only found ${games.length}.` - ) + const games = gamesData.games.slice(0, count) + + if (games.length < count) { + throw new Error( + `Requested ${count} games, but only found ${games.length}.` + ) + } + + for (const game of games) { + await graphql( + request, + ` + mutation($userId: Int!, $gameId: Int!) { + addToWishlist(userId: $userId, gameId: $gameId) } + `, + { + userId, + gameId: game.appid, + }, + targetUser.token + ) + } + } + + await use(seedWishlist) +}, + seedReview: async ({ request, user }, use) => { + const seedReview = async (userId: number) => { + if (userId !== user.id) { + throw new Error(`No test user with ID ${userId} is available`) + } - for (const game of games) { - // TODO: Replace with your actual wishlist mutation. - await graphql( - request, - ` - mutation($userId: Int!, $gameId: Int!) { - addToWishlist( - userId: $userId, - gameId: $gameId - ) - } - `, - { - userId, - gameId: game.id, - }, - targetUser.token - ) + const gamesData = await graphql( + request, + `query { + games(limit: 1, offset: 0) { + appid } + }`, + {}, + user.token + ) + + const game = gamesData.games[0] + + if (!game) { + throw new Error('No games available to create a test review') } - await use(seedWishlist) - }, + await graphql( + request, + `mutation( + $userId: Int! + $gameId: Int! + $rating: Int! + $text: String! + ) { + createReview( + userId: $userId + gameId: $gameId + rating: $rating + text: $text + ) { + id + } + }`, + { + userId, + gameId: game.appid, + rating: 5, + text: 'Playwright E2E test review' + }, + user.token + ) + } + await use(seedReview) +}, + }) export { expect } \ No newline at end of file diff --git a/E2E/Friendpage.spec.ts b/E2E/Friendpage.spec.ts index 57fe02a..8760f85 100644 --- a/E2E/Friendpage.spec.ts +++ b/E2E/Friendpage.spec.ts @@ -11,45 +11,41 @@ test.describe('FriendPage', () => { await openMainPage(page) await page.getByRole('link', { - name: /friends/i + name: 'Friends', + exact: true }).click() await expect(page).toHaveURL(FRIEND_PAGE) }) - async function addFriend(page: import('@playwright/test').Page, friendId: string, username: string) { + async function addFriend( + page: import('@playwright/test').Page, + friendId: string + ) { const friendInput = page.getByRole('textbox', { - name: /friend id/i + name: /friend id/i }) await friendInput.fill(friendId) await page.getByRole('button', { - name: 'Add', - exact: true + name: 'Add', + exact: true }).click() - // Adding a friend automatically selects them. - const friendSelector = page.getByPlaceholder('Look at a friend') + // The Friend ID field is cleared after a successful add. + await expect(friendInput).toHaveValue('') - await expect(friendSelector).toHaveValue(username) - - // Wait until their wishlist has loaded. + // The selected friend's wishlist has finished loading. await expect(page.locator('.games-grid-wishlist')).toBeVisible() } test('Add a friend', async ({ page, secondUser }) => { - await addFriend(page, secondUser.friendId, secondUser.username) - - await expect( - page.getByPlaceholder('Look at a friend') - ).toHaveValue(secondUser.username) - - await expect(page.locator('.games-grid-wishlist')).toBeVisible() + await addFriend(page, secondUser.friendId) }) test('Friend wishlist pagination', async ({ page, secondUser }) => { - await addFriend(page, secondUser.friendId, secondUser.username) + await addFriend(page, secondUser.friendId) const wishlistGames = page.locator('.games-grid-wishlist > *') @@ -59,7 +55,7 @@ test.describe('FriendPage', () => { const firstPageGame = (await wishlistGames.first().innerText()).trim() const nextPage = page.getByRole('button', { - name: 'Go to page 2' + name: 'Go to page 2' }) await expect(nextPage).toBeVisible() @@ -71,4 +67,4 @@ test.describe('FriendPage', () => { expect(secondPageGame).not.toBe(firstPageGame) }) -}) +}) \ No newline at end of file diff --git a/E2E/Mainpage.spec.ts b/E2E/Mainpage.spec.ts index 2550bdb..8e03701 100644 --- a/E2E/Mainpage.spec.ts +++ b/E2E/Mainpage.spec.ts @@ -1,12 +1,7 @@ - import { test, expect } from './fixtures' import { openMainPage, testCarousel } from './helpers' -const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ const GAME_PAGE = /#\/gamepage\/\d+$/ -const SEARCH_PAGE = /#\/SearchPage$/ - -// MainPage carousels test.describe('MainPage - Carousels', () => { test.beforeEach(async ({ page }) => { @@ -26,48 +21,27 @@ test.describe('MainPage - Carousels', () => { }) test('Discounted games - next and previous buttons', async ({ page }) => { - await testCarousel(page, 'Discounted Games') + await testCarousel(page, 'Discounts by Genre') }) }) // MainPage components - -test('Smoke test - navigate through MainPage components', async ({ page }) => { +test('Navigate from a recent review to its game', async ({ + page, + user, + seedReview +}) => { + await seedReview(user.id) await openMainPage(page) - // Passive game card -> GamePage - const passiveGameCard = page.locator('a[href*="gamepage/"]').first() - - await expect(passiveGameCard).toBeVisible() - await passiveGameCard.click() - - await expect(page).toHaveURL(GAME_PAGE) - - // GamePage -> MainPage using back button - await page.getByRole('button', { - name: /back/i - }).click() - - await expect(page).toHaveURL(MAIN_PAGE) - - // MainPage -> SearchPage - await page.getByRole('link', { - name: /browse our catalog/i - }).click() + const reviewCard = page.locator('.reviewCard').first() - await expect(page).toHaveURL(SEARCH_PAGE) + await expect(reviewCard).toBeVisible() - // SearchPage -> MainPage using back button - await page.getByRole('button', { - name: /back/i + await reviewCard.getByRole('link', { + name: 'See this game', + exact: true }).click() - await expect(page).toHaveURL(MAIN_PAGE) - - // See the game -> GamePage - await page.getByRole('button', { - name: /see this game/i - }).first().click() - await expect(page).toHaveURL(GAME_PAGE) -}) +}) \ No newline at end of file diff --git a/E2E/MainpageToGamepage.spec.ts b/E2E/MainpageToGamepage.spec.ts index fc9613c..3a3e41a 100644 --- a/E2E/MainpageToGamepage.spec.ts +++ b/E2E/MainpageToGamepage.spec.ts @@ -1,9 +1,12 @@ import { test, expect } from './fixtures' -const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ const GAME_PAGE = /#\/gamepage\/\d+$/ +const WISHLIST_PAGE = /#\/WishlistPage$/ -test('open the top game, go back, and toggle the wishlist button', async ({ page, user }) => { +test('open the top game, go back, and toggle the wishlist button', async ({ + page, + user +}) => { expect(user.id).toBeGreaterThan(0) await page.goto('/') @@ -19,27 +22,20 @@ test('open the top game, go back, and toggle the wishlist button', async ({ page await expect(firstGameLink).toBeVisible() const gameName = (await firstGameLink.innerText()).split('\n')[0].trim() - const href = await firstGameLink.getAttribute('href') - - expect(href).toMatch(GAME_PAGE) await firstGameLink.click() await expect(page).toHaveURL(GAME_PAGE) await expect(page.getByRole('heading', { name: gameName }).first()).toBeVisible() - await page.goBack() - await expect(page).toHaveURL(MAIN_PAGE) - - await page.goForward() - await expect(page).toHaveURL(GAME_PAGE) - const addButton = page.getByRole('button', { - name: /add to wishlist/i + name: 'Add to wishlist', + exact: true }) const removeButton = page.getByRole('button', { - name: /remove from wishlist/i + name: 'Remove from wishlist', + exact: true }) await expect(addButton).toBeVisible() @@ -50,4 +46,12 @@ test('open the top game, go back, and toggle the wishlist button', async ({ page await removeButton.click() await expect(addButton).toBeVisible() -}) + + // Navigate to the WishlistPage + await page.getByRole('link', { + name: 'Wishlist', + exact: true + }).click() + + await expect(page).toHaveURL(WISHLIST_PAGE) +}) \ No newline at end of file diff --git a/E2E/Navigation.spec.ts b/E2E/Navigation.spec.ts index 5fb9c04..c4e9986 100644 --- a/E2E/Navigation.spec.ts +++ b/E2E/Navigation.spec.ts @@ -6,14 +6,12 @@ const SEARCH_PAGE = /#\/SearchPage$/ const WISHLIST_PAGE = /#\/WishlistPage$/ const FRIEND_PAGE = /#\/FriendsPage$/ const PROFILE_PAGE = /#\/ProfilePage$/ -const SIGNIN_PAGE = /#\/SignInPage$/ -const SIGNUP_PAGE = /#\/SignUpPage$/ -test('Smoke test - navigate through all header pages', async ({ page }) => { +test('Smoke test - navigate through all header pages', async ({ page, user }) => { await openMainPage(page) // MainPage -> SearchPage - await page.getByRole('link', { name: /browse games/i }).click() + await page.getByRole('link', { name: 'Search', exact: true }).click() await expect(page).toHaveURL(SEARCH_PAGE) // SearchPage -> WishlistPage @@ -28,15 +26,18 @@ test('Smoke test - navigate through all header pages', async ({ page }) => { await page.getByRole('link', { name: 'Profile', exact: true }).click() await expect(page).toHaveURL(PROFILE_PAGE) - // ProfilePage -> SignInPage - await page.getByRole('link', { name: /SignIn|logout/i }).click() - await expect(page).toHaveURL(SIGNIN_PAGE) + // ProfilePage -> Sign Out + await page.getByRole('link', { name: 'Sign Out', exact: true }).click() - // SignInPage -> SignUpPage - await page.getByRole('link', { name: /SignUp|register/i }).click() - await expect(page).toHaveURL(SIGNUP_PAGE) + // Sign Out navigates to MainPage + await expect(page).toHaveURL(MAIN_PAGE) + + // Verify that logout changed the header authentication state + await expect( + page.getByRole('link', { name: 'Sign In', exact: true }) + ).toBeVisible() - // SignUpPage -> MainPage using logo - await page.getByRole('link', { name: /logo|home/i }).click() + // MainPage -> Home using logo + await page.getByRole('link', { name: 'GameStart home' }).click() await expect(page).toHaveURL(MAIN_PAGE) }) diff --git a/E2E/Profilepage.spec.ts b/E2E/Profilepage.spec.ts index 92beb0c..64816e5 100644 --- a/E2E/Profilepage.spec.ts +++ b/E2E/Profilepage.spec.ts @@ -1,29 +1,36 @@ + import { test, expect } from './fixtures' -test('User can edit their profile', async ({ page }) => { - await page.goto('/#/ProfilePage') +test('User can edit their profile', async ({ page, user }) => { + await page.goto('/#/ProfilePage') + + // Confirm the profile page has loaded + await expect( + page.getByRole('heading', { name: 'Profile', exact: true }) + ).toBeVisible() + + // Open profile editor + await expect( + page.getByRole('button', { name: 'Edit profile', exact: true }) + ).toBeVisible() - // Open profile editor - await page.getByRole('button', { - name: 'Edit profile', - exact: true, - }).click() + await page.getByRole('button', { + name: 'Edit profile', + exact: true, + }).click() - // Change description - const newDescription = 'This is my updated profile description.' + const newDescription = 'This is my updated profile description.' - await page.getByRole('textbox', { - name: 'Description', - }).fill(newDescription) + await page.getByRole('textbox', { + name: 'Description', + }).fill(newDescription) - // Save profile - await page.getByRole('button', { - name: 'Save profile', - exact: true, - }).click() + await page.getByRole('button', { + name: 'Save profile', + exact: true, + }).click() - // Verify updated description - await expect( - page.getByText(newDescription, { exact: true }) - ).toBeVisible() + await expect( + page.getByText(newDescription, { exact: true }) + ).toBeVisible() }) diff --git a/E2E/Reviews.spec.ts b/E2E/Reviews.spec.ts index 31b26e9..d5b99cb 100644 --- a/E2E/Reviews.spec.ts +++ b/E2E/Reviews.spec.ts @@ -1,65 +1,29 @@ import { test, expect } from './fixtures' import { openMainPage } from './helpers' -const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ const GAME_PAGE = /#\/gamepage\/\d+$/ -test('MainPage - write a review and check Recent Reviews', async ({ page, user }) => { - expect(user.id).toBeGreaterThan(0) - +test('Recent Reviews - navigate to a game', async ({ + page, + user, + seedReview +}) => { + await seedReview(user.id) await openMainPage(page) const reviewsSection = page.locator('section.main-page-reviews') - await expect(reviewsSection.getByRole('heading', { - name: /recent reviews/i - })).toBeVisible() - - await expect(reviewsSection.getByText('Loading reviews...')).toHaveCount(0) + await expect( + reviewsSection.getByRole('heading', { name: /recent reviews/i }) + ).toBeVisible() const seeGameLink = reviewsSection.getByRole('link', { - name: /see this game/i + name: 'See this game', + exact: true }).first() await expect(seeGameLink).toBeVisible() await seeGameLink.click() await expect(page).toHaveURL(GAME_PAGE) - - const writeReviewButton = page.getByRole('button', { - name: /write review/i - }) - - await expect(writeReviewButton).toBeVisible() - await writeReviewButton.click() - - const reviewText = `Automated test review ${Date.now()}` - - const reviewInput = page.getByRole('textbox', { - name: /review|comment/i - }) - - await reviewInput.fill(reviewText) - - const rating = page.getByRole('button', { - name: /5 stars|5 star/i - }) - - if (await rating.count()) { - await rating.click() - } - - await page.getByRole('button', { - name: /submit review|post review|save review/i - }).click() - - // Return to MainPage using the header logo. - await page.getByRole('link', { name: /logo|home/i }).click() - - await expect(page).toHaveURL(MAIN_PAGE) - - const recentReviews = page.locator('section.main-page-reviews') - - await expect(recentReviews.getByText('Loading reviews...')).toHaveCount(0) - await expect(recentReviews).toContainText(reviewText) -}) +}) \ No newline at end of file diff --git a/E2E/Searchpage.spec.ts b/E2E/Searchpage.spec.ts index 1ac45d4..f8e8dc8 100644 --- a/E2E/Searchpage.spec.ts +++ b/E2E/Searchpage.spec.ts @@ -37,31 +37,40 @@ test('Search with no matching results', async ({ page }) => { await expect(page.getByText('No games found.')).toBeVisible() }) - test('Filter games by genre', async ({ page }) => { - await page.getByRole('button', { + const toggle = page.getByRole('button', { name: 'Toggle filters', - }).click() - - const filter = page.getByRole('combobox', { - name: 'Filter by genre', }) + // Ensure the filter panel is open. + if (await toggle.getAttribute('aria-pressed') !== 'true') { + await toggle.click() + } + + const filter = page.getByTestId('genre-filter-select') + await expect(filter).toBeVisible() + + // Open the genre dropdown. await filter.click() - const options = page.getByRole('option') - await expect(options.first()).toBeVisible() + // Wait for the genre options to appear. + const firstOption = page.getByRole('option').first() + + await expect(firstOption).toBeVisible() - const firstOption = options.first() const genreName = (await firstOption.innerText()).trim() + // Select the first genre. await firstOption.click() - // MUI multiple Select displays the selected genre. + // Verify that the selected genre is displayed. await expect(filter).toContainText(genreName) - // Wait for the filtered game results to finish loading. + // Verify that the filter panel remains open. + await expect(page.locator('.filtersection')).toBeVisible() + + // Wait for games to finish loading. await expect(page.getByText('Loading games...')).toHaveCount(0) }) @@ -88,25 +97,32 @@ test('Sort games', async ({ page }) => { test('User can navigate between pages of search results', async ({ page }) => { const gameCards = page.locator('.games-grid-searchpage > *') + const pagination = page.locator('.pageinationSearch') await expect(gameCards).toHaveCount(12) - // Store the first game's actual displayed text on page 1 - const firstPageFirstGame = await gameCards.first().innerText() + const firstPageFirstGame = (await gameCards.first().innerText()) + .replace(/\s+/g, ' ') + .trim() - await page.getByRole('button', { name: 'Go to page 2' }).click() + // Navigate to page 2 + await pagination.getByRole('button', { name: 'Go to page 2' }).click() - await expect(gameCards).toHaveCount(12) + await expect.poll(async () => { + return (await gameCards.first().innerText()) + .replace(/\s+/g, ' ') + .trim() + }).not.toBe(firstPageFirstGame) - // Wait until the first game changes - await expect(async () => { - const secondPageFirstGame = await gameCards.first().innerText() - expect(secondPageFirstGame).not.toBe(firstPageFirstGame) - }).toPass() + await expect(gameCards).toHaveCount(12) - await page.getByRole('button', { name: 'Go to page 1' }).click() + // Return to page 1 + await pagination.getByRole('button', { name: 'Go to page 1' }).click() - // Verify that page 1 is restored - await expect(gameCards.first()).toHaveText(firstPageFirstGame) - }) + await expect.poll(async () => { + return (await gameCards.first().innerText()) + .replace(/\s+/g, ' ') + .trim() + }).toBe(firstPageFirstGame) +}) }) diff --git a/E2E/Wishlist.spec.ts b/E2E/Wishlist.spec.ts index 980f43e..83bc184 100644 --- a/E2E/Wishlist.spec.ts +++ b/E2E/Wishlist.spec.ts @@ -12,7 +12,8 @@ test.describe('WishlistPage', () => { await openMainPage(page) await page.getByRole('link', { - name: /wishlist/i, + name: 'Wishlist', + exact: true, }).click() await expect(page).toHaveURL(WISHLIST_PAGE) diff --git a/E2E/helpers.ts b/E2E/helpers.ts index 66652bc..faf1656 100644 --- a/E2E/helpers.ts +++ b/E2E/helpers.ts @@ -1,45 +1,77 @@ -import { expect } from './fixtures' +import { expect, type Page } from './Fixtures' const MAIN_PAGE = /^http:\/\/localhost:5173\/(#\/)?$/ -// Reusable helpers - -export async function openMainPage(page: any) { +export async function openMainPage(page: Page) { await page.goto('/') await expect(page).toHaveURL(MAIN_PAGE) } -export async function getSection(page: any, heading: string) { - return page.getByRole('heading', { name: heading }) - .locator('xpath=ancestor::section[1]') +export async function getSection(page: Page, heading: string) { + const headingLocator = page.getByRole('heading', { + name: heading, + exact: true + }) + + await expect(headingLocator).toBeVisible() + + return headingLocator.locator('xpath=ancestor::section[1]') } -export async function testCarousel(page: any, heading: string) { +export async function testCarousel(page: Page, heading: string) { const section = await getSection(page, heading) const nextButton = section.getByRole('button', { - name: /next|right/i + name: 'Next', + exact: true }) const previousButton = section.getByRole('button', { - name: /previous|prev|left/i + name: 'Previous', + exact: true }) + const gameCards = section.locator('.genre-games-row a[href*="gamepage/"]') + await expect(nextButton).toBeVisible() await expect(previousButton).toBeVisible() - const initialContent = await section.innerText() + // Wait until the games have finished loading. + await expect(section.getByText(/loading/i)).toHaveCount(0) + + const initialCount = await gameCards.count() + + if (initialCount === 0) { + await expect(nextButton).toBeDisabled() + await expect(previousButton).toBeDisabled() + return + } + + const initialGames = await gameCards.allInnerTexts() + + // If there are not enough games for another page, + // the carousel should not allow moving forward. + if (await nextButton.isDisabled()) { + await expect(previousButton).toBeDisabled() + return + } await nextButton.click() - await expect(section).not.toHaveText(initialContent) + + await expect.poll(async () => { + return gameCards.allInnerTexts() + }).not.toEqual(initialGames) + + await expect(previousButton).toBeEnabled() await previousButton.click() - await expect(section).toContainText( - initialContent.split('\n')[0] - ) + + await expect.poll(async () => { + return gameCards.allInnerTexts() + }).toEqual(initialGames) } -export async function goBackToMain(page: any) { +export async function goBackToMain(page: Page) { await page.goBack() await expect(page).toHaveURL(MAIN_PAGE) } \ No newline at end of file diff --git a/Frontend/src/pages/SearchPage.tsx b/Frontend/src/pages/SearchPage.tsx index 6963314..5b62886 100644 --- a/Frontend/src/pages/SearchPage.tsx +++ b/Frontend/src/pages/SearchPage.tsx @@ -259,6 +259,7 @@ export function SearchPage() { Filter by genre