Files
joke-app/e2e/chat.e2e.ts
EJClaw 65c56d3ae7 채팅: 가리기 삭제, 100줄이 찬 뒤에도 맨 아래 고정(+새 메시지 수), 이름 줄과 말풍선으로 이름·내용 구분
- 공통 ChatMessage(이름 줄 + 말풍선, 내 말은 오른쪽, 이어 말하면 이름 한 번) — 방 채팅·마피아·라이어 게임, 그림 맞히기 이름 표시
- useStickToBottom: 개수 대신 목록 내용 변화를 보고 맨 아래 유지, 위로 올려 읽는 중엔 그대로, 보내면 다시 맨 아래
- 휴대폰 채팅 버튼의 새 메시지 수도 100줄 뒤에 0이 되던 문제(마지막 본 id 기준으로)
- e2e/chat.e2e.ts: PC 대기실·게임 옆 칸·휴대폰 시트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:49:03 +09:00

192 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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<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;
}
};
/** Send one chat line through the input (the server allows one line per 0.5 s per person). */
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<HTMLElement>(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('게임 중(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);