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

327 lines
18 KiB
TypeScript
Raw Permalink 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) + narrowed PC window (720–1099px) chat button
* + chat sound on live lines only.
* 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. */
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('빠르게 여러 번 Enter: 제한 없이 전부 순서대로, 바로 들어감', async () => {
await a.waitForTimeout(1500);
const input = a.locator('.chat-panel input[aria-label="메시지"]').first();
const N = 20;
const t0 = performance.now();
for (let i = 1; i <= N; i++) {
await input.fill(`연타 ${i}`);
await input.press('Enter');
}
await a.locator('.chat-line .chat-text', { hasText: new RegExp(`^연타 ${N}$`) }).waitFor({ timeout: 10_000 });
// No pace limit any more: 20 lines in a row (well past the old 6-line burst) all show right away.
const ms = performance.now() - t0;
if (ms > 2000) throw new Error(`${N} quick lines took ${Math.round(ms)}ms to show`);
console.log(` ${N} quick lines shown in ${Math.round(ms)}ms`);
const got = await a.locator('.chat-line .chat-text', { hasText: /^연타 \d+$/ }).allInnerTexts();
const want = Array.from({ length: N }, (_, i) => `연타 ${i + 1}`);
if (got.join(',') !== want.join(',')) throw new Error(`order/lost: ${got.join(',')}`);
// The other side got them all too (phone sheet closed: the badge counts them).
await b.getByRole('button', { name: `채팅, 새 메시지 ${N}개` }).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');
// Tapping 보내기 (not the keyboard's send key) must not take the focus either, or the phone keyboard drops.
await input.pressSequentially('버튼으로 보냄');
await sheet.getByRole('button', { name: '보내기' }).tap();
await sheet.locator('.chat-line', { hasText: '버튼으로 보냄' }).waitFor();
await b.waitForTimeout(150);
if (!(await input.evaluate((el) => el === document.activeElement))) throw new Error('the chat box lost focus after tapping 보내기');
await sheet.getByRole('button', { name: '닫기' }).click();
});
await step('PC 창을 줄여도(720~1099px) 채팅 버튼으로 채팅을 볼 수 있음', async () => {
for (const width of [900, 760]) {
await a.setViewportSize({ width, height: 900 });
await a.waitForTimeout(150);
if (await a.locator('.chat-panel').count()) throw new Error(`${width}px: unexpected inline chat panel`);
await a.locator('.room-bar').getByRole('button', { name: /^채팅/ }).click();
const sheet = a.getByRole('dialog', { name: '채팅' });
await sheet.locator('.chat-line', { hasText: '치는 중 계속' }).waitFor();
await say(a, `줄인 창 ${width}`);
await sheet.locator('.chat-line', { hasText: `줄인 창 ${width}` }).waitFor();
if (width === 900) await a.screenshot({ path: join(SHOTS, 'chat-sheet-pc-narrow.png') });
await sheet.getByRole('button', { name: '닫기' }).click();
}
// Wide again: the side panel is back and the bar button goes away.
await a.setViewportSize({ width: 1440, height: 900 });
await a.locator('.chat-panel').first().waitFor();
if (await a.locator('.room-bar').getByRole('button', { name: /^채팅/ }).count()) throw new Error('chat button still on the wide bar');
});
await step('채팅 소리: 새 줄마다 "뽁"(보낸 사람도), 다시 들어올 때 받는 지난 줄은 조용히', async () => {
// Count the chat sound's bubble (starts at 380 Hz) as it is scheduled.
const rec = () => {
const w = window as unknown as { __chatBeeps: number };
w.__chatBeeps = 0;
const orig = AudioParam.prototype.setValueAtTime;
AudioParam.prototype.setValueAtTime = function (v: number, t: number) {
if (v === 380) w.__chatBeeps++;
return orig.call(this, v, t);
};
};
const beeps = (p: Page) => p.evaluate(() => (window as unknown as { __chatBeeps: number }).__chatBeeps);
await b.addInitScript(rec);
await a.evaluate(rec);
await b.evaluate(rec);
await a.waitForTimeout(200);
await say(a, '소리 확인');
await b.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 });
await a.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 });
// Reload: the room resends its chat history, which must not beep.
await b.reload();
await b.getByRole('button', { name: /^채팅/ }).click();
const sheet = b.getByRole('dialog', { name: '채팅' });
await sheet.locator('.chat-line', { hasText: '소리 확인' }).waitFor();
await b.waitForTimeout(500);
if ((await beeps(b)) !== 0) throw new Error(`history beeped ${await beeps(b)} times`);
await say(a, '다시 들어온 뒤');
await sheet.locator('.chat-line', { hasText: '다시 들어온 뒤' }).waitFor();
await b.waitForFunction(() => (window as unknown as { __chatBeeps: number }).__chatBeeps === 1, null, { timeout: 5000 });
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);