/** * E2E: the room chat stays at the newest line (also after more than 100 lines, when the list is full), lets the reader * scroll up without jumping, shows who said what as a name line + bubble, and has no "가리기" button any more. * PC lobby + PC in-game side panel + phone chat sheet (unread badge past 100 lines too). * Run: E2E_PORT=4641 bun e2e/chat.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 ?? 4641); 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) => { 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; } }; /** Send one chat line through the input. */ async function say(p: Page, text: string) { const input = p.locator('.chat-panel input[aria-label="메시지"]').first(); await input.fill(text); await input.press('Enter'); } /** The list is scrolled to its end and the newest line is inside the list's visible box (and the window). */ async function atBottom(p: Page, list = '.chat-list') { return p.evaluate((sel) => { const el = [...document.querySelectorAll(sel)].find((e) => e.offsetParent !== null); if (!el) return { ok: false, why: 'no list' }; const last = el.lastElementChild as HTMLElement | null; const gap = el.scrollHeight - el.scrollTop - el.clientHeight; if (!last) return { ok: false, why: 'empty' }; const lb = last.getBoundingClientRect(); const eb = el.getBoundingClientRect(); const inList = lb.bottom <= eb.bottom + 2 && lb.top >= eb.top - 2; const inWindow = lb.bottom <= window.innerHeight + 2 && lb.top >= 0; return { ok: gap <= 2 && inList && inWindow, why: `gap ${gap}, inList ${inList}, inWindow ${inWindow}, last "${last.textContent}"` }; }, list); } async function expectBottom(p: Page, label: string) { // Give the observer a frame. await p.waitForTimeout(120); const r = await atBottom(p); if (!r.ok) throw new Error(`${label}: not at the newest line (${r.why})`); } try { const ctxA = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' }); const ctxB = await browser.newContext({ viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'ko-KR' }); const a = await ctxA.newPage(); const b = await ctxB.newPage(); const errors: string[] = []; for (const p of [a, b]) p.on('pageerror', (e) => errors.push(e.message)); for (const p of [a, b]) await p.addInitScript(() => localStorage.setItem('bg:qs:omok', '1')); let code = ''; await step('A 방 만들기, B 휴대폰으로 입장', async () => { await a.goto(ORIGIN + '/'); await a.getByRole('button', { name: '+ 방 만들기' }).click(); await a.getByRole('dialog', { name: '게임 고르기' }).getByRole('button', { name: /오목/ }).click(); await a.getByLabel('내 이름(닉네임)').fill('호랑이'); await a.getByRole('button', { name: '이 이름으로 시작하기' }).click(); await a.waitForURL(/\/r\/\d{6}$/); code = a.url().slice(-6); await b.goto(`${ORIGIN}/r/${code}`); await b.getByLabel('내 이름(닉네임)').fill('고양이'); await b.getByRole('button', { name: '이 이름으로 입장하기' }).click(); await a.getByLabel('자리').getByText('고양이').waitFor(); }); await step('대기실(PC): 110줄이 넘어도 맨 아래 고정, 이름과 말풍선 구분, 가리기 없음', async () => { // B talks from the chat sheet on the phone; A from the inline panel. 2 people × 0.55 s ≈ 110 lines in 30 s. await b.getByRole('button', { name: /^채팅/ }).click(); const sheet = b.getByRole('dialog', { name: '채팅' }); await sheet.waitFor(); const count = () => a.locator('.chat-list .chat-line').count(); let extra = 0; for (let i = 1; i <= 90 && extra < 6; i++) { await Promise.all([say(a, `호랑이 메시지 ${i}`), (async () => { const input = sheet.locator('input[aria-label="메시지"]'); await input.fill(`고양이 메시지 ${i}${i % 9 === 0 ? ' — 조금 긴 문장도 줄이 바뀌어서 말풍선 안에 잘 들어가는지 확인해요.' : ''}`); await input.press('Enter'); })()]); await a.waitForTimeout(600); // Keep going a few rounds after the list is full (100 lines): that is when following new lines used to stop. if ((await count()) >= 100) extra++; } if (extra < 6) throw new Error(`the list never filled up (${await count()} lines)`); await sheet.locator('input[aria-label="메시지"]').fill('꽉 찬 뒤의 마지막 메시지'); await sheet.locator('input[aria-label="메시지"]').press('Enter'); await a.locator('.chat-line', { hasText: '꽉 찬 뒤의 마지막 메시지' }).waitFor(); await expectBottom(a, 'PC lobby'); await expectBottom(b, 'phone sheet'); if (await a.getByRole('button', { name: '가리기' }).count()) throw new Error('가리기 button still there'); if (await a.getByText('가리기', { exact: true }).count()) throw new Error('가리기 text still there'); // Someone else's line: a name line and a separate bubble. My own: right side, no visible name. const other = a.locator('.chat-line:not(.mine):not(.cont)', { hasText: '고양이 메시지' }).last(); await other.locator('.chat-name').waitFor(); if ((await other.locator('.chat-name').innerText()) !== '고양이') throw new Error('name line text'); const nb = (await other.locator('.chat-name').boundingBox())!; const tb = (await other.locator('.chat-text').boundingBox())!; if (!(nb.y + nb.height <= tb.y + 1)) throw new Error('name is not above the bubble'); const mine = a.locator('.chat-line.mine').last(); if (((await mine.locator('.chat-name').boundingBox())?.width ?? 0) > 1) throw new Error('my own name should be visually hidden (screen readers only)'); const lb = (await a.locator('.chat-list').boundingBox())!; const mb = (await mine.locator('.chat-text').boundingBox())!; if (mb.x + mb.width < lb.x + lb.width - 30) throw new Error('my bubble is not on the right'); await a.screenshot({ path: join(SHOTS, 'chat-lobby-pc.png') }); await b.screenshot({ path: join(SHOTS, 'chat-sheet-phone.png') }); }); await step('위로 올려 읽는 중에는 새 메시지가 와도 그대로, 내가 보내면 다시 맨 아래', async () => { await a.locator('.chat-list').evaluate((el) => (el.scrollTop = 0)); await a.waitForTimeout(100); await b.getByRole('dialog', { name: '채팅' }).locator('input[aria-label="메시지"]').fill('읽는 중에 온 메시지'); await b.getByRole('dialog', { name: '채팅' }).locator('input[aria-label="메시지"]').press('Enter'); await a.locator('.chat-line', { hasText: '읽는 중에 온 메시지' }).waitFor({ state: 'attached' }); await a.waitForTimeout(150); const top = await a.locator('.chat-list').evaluate((el) => el.scrollTop); if (top > 5) throw new Error(`jumped while reading (scrollTop ${top})`); await say(a, '이제 다시 아래로'); await a.locator('.chat-line', { hasText: '이제 다시 아래로' }).waitFor(); await expectBottom(a, 'after sending'); }); await step('휴대폰: 시트를 닫아도 새 메시지 수(100줄이 꽉 찬 뒤에도), 다시 열면 맨 아래', async () => { const sheet = b.getByRole('dialog', { name: '채팅' }); await sheet.getByRole('button', { name: '닫기' }).click(); await a.waitForTimeout(600); for (let i = 1; i <= 3; i++) { await say(a, `안 읽은 메시지 ${i}`); await a.waitForTimeout(560); } await b.getByRole('button', { name: '채팅, 새 메시지 3개' }).waitFor({ timeout: 5000 }); await b.getByRole('button', { name: /^채팅/ }).click(); await sheet.locator('.chat-line', { hasText: '안 읽은 메시지 3' }).waitFor(); await expectBottom(b, 'phone sheet reopened'); await b.emulateMedia({ colorScheme: 'dark' }); await b.waitForTimeout(200); await b.screenshot({ path: join(SHOTS, 'chat-sheet-phone-dark.png') }); await b.emulateMedia({ colorScheme: 'light' }); await sheet.getByRole('button', { name: '닫기' }).click(); await b.getByRole('button', { name: '채팅', exact: true }).waitFor(); }); await step('빠르게 여러 번 Enter: 전부 순서대로, 바로 들어감', async () => { await a.waitForTimeout(1500); const input = a.locator('.chat-panel input[aria-label="메시지"]').first(); const t0 = performance.now(); for (let i = 1; i <= 7; i++) { await input.fill(`연타 ${i}`); await input.press('Enter'); } for (let i = 1; i <= 7; i++) await a.locator('.chat-line', { hasText: `연타 ${i}` }).waitFor({ timeout: 10_000 }); // Lines used to go out one per 0.55 s (7 lines ≈ 3.3 s); now a quick run goes at once. const ms = performance.now() - t0; if (ms > 1500) throw new Error(`7 quick lines took ${Math.round(ms)}ms to show`); console.log(` 7 quick lines shown in ${Math.round(ms)}ms`); const got = await a.locator('.chat-line .chat-text', { hasText: /^연타 \d$/ }).allInnerTexts(); if (got.join(',') !== [1, 2, 3, 4, 5, 6, 7].map((i) => `연타 ${i}`).join(',')) throw new Error(`order/lost: ${got.join(',')}`); // The other side got them all too (phone sheet closed: the badge counts 7). await b.getByRole('button', { name: '채팅, 새 메시지 7개' }).waitFor({ timeout: 5000 }); }); await step('사람도 "입력 중" 표시: 치는 동안 보이고, 보내면 사라짐', async () => { const input = a.locator('.chat-panel input[aria-label="메시지"]').first(); await input.fill('지금 치는 중'); await b.getByRole('button', { name: /^채팅/ }).click(); const sheet = b.getByRole('dialog', { name: '채팅' }); await sheet.locator('[data-person]', { hasText: '호랑이 입력 중' }).waitFor({ timeout: 5000 }); await b.waitForTimeout(300); await b.screenshot({ path: join(SHOTS, 'chat-typing-phone.png') }); await input.press('Enter'); await sheet.locator('[data-person]').waitFor({ state: 'detached', timeout: 5000 }); // Nobody sees their own typing. await sheet.locator('input[aria-label="메시지"]').fill('나도 치는 중'); await a.locator('[data-person]', { hasText: '고양이 입력 중' }).waitFor({ timeout: 5000 }); if (await b.locator('[data-person]', { hasText: '고양이' }).count()) throw new Error('sees own typing'); await sheet.locator('input[aria-label="메시지"]').fill(''); await a.locator('[data-person]').waitFor({ state: 'detached', timeout: 5000 }); await sheet.getByRole('button', { name: '닫기' }).click(); }); await step('휴대폰 채팅 시트: 새 메시지가 와도 입력 칸 포커스(키보드)가 그대로', async () => { await b.getByRole('button', { name: /^채팅/ }).click(); const sheet = b.getByRole('dialog', { name: '채팅' }); const input = sheet.locator('input[aria-label="메시지"]'); await input.click(); await input.pressSequentially('치는 중'); for (let i = 1; i <= 3; i++) { await say(a, `치는 동안 온 메시지 ${i}`); await sheet.locator('.chat-line', { hasText: `치는 동안 온 메시지 ${i}` }).waitFor(); } await b.waitForTimeout(150); if (!(await input.evaluate((el) => el === document.activeElement))) throw new Error('the chat box lost focus when a line arrived'); await input.pressSequentially(' 계속'); await input.press('Enter'); await sheet.locator('.chat-line', { hasText: '치는 중 계속' }).waitFor(); if (!(await input.evaluate((el) => el === document.activeElement))) throw new Error('the chat box lost focus after sending'); await sheet.getByRole('button', { name: '닫기' }).click(); }); await step('소리 크기: 방 막대 오른쪽 위, 기본 50, 0~100', async () => { const btn = a.locator('.room-bar').getByRole('button', { name: /^소리 크기/ }); if ((await btn.getAttribute('aria-label')) !== '소리 크기 50') throw new Error(`default: ${await btn.getAttribute('aria-label')}`); await btn.click(); const slider = a.getByRole('slider', { name: '소리 크기 (0~100)' }); if ((await slider.getAttribute('min')) !== '0' || (await slider.getAttribute('max')) !== '100') throw new Error('range'); await slider.fill('30'); await a.locator('.room-bar').getByRole('button', { name: '소리 크기 30' }).waitFor(); await a.waitForTimeout(300); await a.screenshot({ path: join(SHOTS, 'volume-room-pc.png') }); await a.keyboard.press('Escape'); const saved = await a.evaluate(() => JSON.parse(localStorage.getItem('bg.settings') ?? '{}').volume); if (saved !== 30) throw new Error(`not saved: ${saved}`); // Phone room bar has it too. await b.locator('.room-bar').getByRole('button', { name: /^소리 크기/ }).waitFor(); await b.screenshot({ path: join(SHOTS, 'volume-roombar-phone.png') }); }); await step('게임 중(PC 옆 칸): 새 메시지마다 맨 아래', async () => { await a.getByRole('button', { name: '▶ 게임 시작' }).click(); await a.getByRole('button', { name: '시작하기' }).click(); await a.locator('.game-side .chat-list').waitFor(); await expectBottom(a, 'game side on open'); for (let i = 1; i <= 6; i++) { await say(a, `게임 중 메시지 ${i}`); await a.waitForTimeout(560); await expectBottom(a, `game side #${i}`); } await a.screenshot({ path: join(SHOTS, 'chat-game-pc.png') }); await a.emulateMedia({ colorScheme: 'dark' }); await a.waitForTimeout(200); await a.screenshot({ path: join(SHOTS, 'chat-game-pc-dark.png') }); }); 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);