Files
joke-app/e2e/settings.e2e.ts

160 lines
8.3 KiB
TypeScript

/**
* E2E: 설정 opens as a popup, so opening it in the middle of a game keeps me in the room.
* - Phone, 오목 against the computer: room bar ⚙️ 설정 → dialog over the board; the address stays, no `leave`/`detach` goes to
* the server, a change applies at once, and Escape / backdrop / 닫기 all close it with focus back on ⚙️.
* - PC header account menu → ⚙️ 설정 is the same popup (with a link to the full 설정 page), and /me still works.
* Run: E2E_PORT=4645 bun e2e/settings.e2e.ts (needs apps/web/dist built)
*/
import { chromium, type Page } from 'playwright-core';
import { mkdirSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
const PORT = Number(process.env.E2E_PORT ?? 4645);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-'));
const app = startServer({
config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN }),
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
});
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
let failed = false;
const step = async (name: string, fn: () => Promise<void>) => {
const t0 = performance.now();
try {
await fn();
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
} catch (e) {
failed = true;
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
throw e;
}
};
/** Every socket message the page sends, as text. */
function recordSent(p: Page): string[] {
const sent: string[] = [];
p.on('websocket', (ws) => ws.on('framesent', (f) => sent.push(String(f.payload))));
return sent;
}
const leftRoom = (sent: string[]) => sent.filter((m) => /"t":"(leave|detach)"/.test(m));
const focusedLabel = (p: Page) => p.evaluate(() => document.activeElement?.getAttribute('aria-label') ?? document.activeElement?.tagName ?? '');
/** 오목 against the computer, game started; returns the room address. */
async function practiceGame(p: Page, name: string): Promise<string> {
await p.goto(`${ORIGIN}/g/omok`);
await p.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click();
await p.getByLabel('내 이름(닉네임)').fill(name);
await p.getByRole('button', { name: '이 이름으로 시작하기' }).click();
await p.waitForURL(/\/r\/\d{6}$/);
await p.getByRole('button', { name: '▶ 게임 시작' }).click();
await p.locator('svg[role="grid"]').waitFor();
return p.url();
}
try {
const phone = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'ko-KR' });
await phone.addInitScript(() => localStorage.setItem('bg:qs:omok', '1'));
const a = await phone.newPage();
const errors: string[] = [];
a.on('pageerror', (e) => errors.push(e.message));
const sent = recordSent(a);
let roomUrl = '';
await step('휴대폰: 컴퓨터와 오목을 시작', async () => {
roomUrl = await practiceGame(a, '설정맨');
});
const opener = () => a.locator('.room-bar').getByRole('button', { name: '글자 크기 · 소리 설정' });
const dialog = () => a.getByRole('dialog', { name: '설정' });
await step('게임 중 ⚙️ 설정 → 팝업, 주소 그대로, 나가기·떠나기 신호 없음, 바꾸면 바로 적용', async () => {
await opener().click();
await dialog().waitFor();
if (a.url() !== roomUrl) throw new Error(`navigated to ${a.url()}`);
if ((await dialog().getAttribute('aria-modal')) !== 'true') throw new Error('dialog is not aria-modal');
if (!(await dialog().evaluate((el) => el.contains(document.activeElement)))) throw new Error('focus did not move into the popup');
// The board is still mounted underneath (the room did not unmount).
if (!(await a.locator('svg[role="grid"]').count())) throw new Error('board went away');
// No account link inside a room: following it would leave.
if (await dialog().getByRole('link', { name: /내 계정/ }).count()) throw new Error('account link shown inside a room');
await dialog().getByRole('group', { name: '글자 크기' }).getByRole('button', { name: '크게', exact: true }).click();
if ((await a.evaluate(() => document.documentElement.dataset.fontScale)) !== 'large') throw new Error('font size not applied at once');
await a.screenshot({ path: join(SHOTS, 'settings-popup-phone.png') });
});
await step('Escape로 닫으면 ⚙️로 초점이 돌아오고 판이 그대로', async () => {
await a.keyboard.press('Escape');
await dialog().waitFor({ state: 'detached' });
if ((await focusedLabel(a)) !== '글자 크기 · 소리 설정') throw new Error(`focus went to ${await focusedLabel(a)}`);
await a.locator('svg[role="grid"]').waitFor();
});
await step('바깥(어두운 곳)을 누르거나 [닫기]를 눌러도 닫혀요', async () => {
await opener().click();
await dialog().waitFor();
await a.mouse.click(195, 30); // the backdrop above the bottom sheet
await dialog().waitFor({ state: 'detached' });
await opener().click();
await dialog().getByRole('button', { name: '닫기' }).click();
await dialog().waitFor({ state: 'detached' });
if (a.url() !== roomUrl) throw new Error(`navigated to ${a.url()}`);
});
await step('방에 그대로 있어요: 신호 없음, 다시 불러와도 같은 크기 글자', async () => {
const bad = leftRoom(sent);
if (bad.length) throw new Error(`sent ${bad.join(', ')}`);
if (!sent.some((m) => /"t":"join"/.test(m))) throw new Error('socket frames were not recorded');
await a.locator('.turn-status').waitFor();
await a.reload();
await a.locator('svg[role="grid"]').waitFor();
if ((await a.evaluate(() => document.documentElement.dataset.fontScale)) !== 'large') throw new Error('font size not saved');
});
await step('PC 헤더 계정 메뉴 → ⚙️ 설정도 팝업, 계정 링크로 설정 페이지', async () => {
const pc = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR' });
await pc.addInitScript(() => localStorage.setItem('bg:qs:omok', '1'));
const b = await pc.newPage();
b.on('pageerror', (e) => errors.push(e.message));
await practiceGame(b, '헤더맨');
await b.goto(`${ORIGIN}/games`);
await b.getByRole('button', { name: /^내 계정/ }).click();
await b.getByRole('menuitem', { name: '⚙️ 설정' }).click();
const d = b.getByRole('dialog', { name: '설정' });
await d.waitFor();
if (!b.url().endsWith('/games')) throw new Error(`navigated to ${b.url()}`);
await d.getByRole('group', { name: '화면 색' }).getByRole('button', { name: '어둡게' }).click();
if ((await b.evaluate(() => document.documentElement.dataset.theme)) !== 'dark') throw new Error('theme not applied at once');
await b.waitForTimeout(400); // let the colour transition finish for the screenshot
await b.screenshot({ path: join(SHOTS, 'settings-popup-pc.png') });
await b.keyboard.press('Escape');
await d.waitFor({ state: 'detached' });
if (!/^내 계정/.test(await focusedLabel(b))) throw new Error(`focus went to ${await focusedLabel(b)}`);
await b.getByRole('button', { name: /^내 계정/ }).click();
await b.getByRole('menuitem', { name: '⚙️ 설정' }).click();
await d.getByRole('link', { name: /내 계정 · 기록 보기/ }).click();
await b.waitForURL(`${ORIGIN}/me`);
await d.waitFor({ state: 'detached' });
// The page keeps the same settings (still dark after the popup changed it).
await b.getByRole('heading', { name: '화면 설정' }).waitFor();
if ((await b.getByRole('group', { name: '화면 색' }).getByRole('button', { name: '어둡게' }).getAttribute('aria-pressed')) !== 'true') throw new Error('page does not show the popup change');
await pc.close();
});
if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`);
} catch (e) {
failed = true;
console.error(e);
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);