d3ro-voice/apps/desktop/tests/e2e/support/electron-app.ts
Yun Chan 7fe49c437e chore: land in-progress workspace changes before 1.16.2
The tree carried uncommitted work from several areas (web push, mobile
screens, admin charts, test-hygiene cleanup, CI and map docs). It is landed
as one commit so the release pipeline can start from a clean tree; the
desktop transcript-correction behaviour shipped in the previous commit and
is unchanged here.
2026-11-05 21:58:44 +09:00

148 lines
5.7 KiB
TypeScript

// apps/desktop/tests/e2e/support/electron-app.ts
// 데스크톱 E2E 의 단일 진입점.
//
// 이 픽스처가 책임지는 것:
// 1. `out/main/index.js` 빌드 산출물 확인 (없으면 "빌드부터 하라"는 메시지로 즉시 실패)
// 2. 테스트마다 고유한 user-data 디렉터리 → 스펙 간 오염·순서 의존 제거 (Playwright Best Practices: isolation)
// 3. 메인 창 판별(팝업 창 제외)과 온보딩 우회를 한 곳에서
// 4. 렌더러 pageerror/console error 수집 → 각 테스트가 마지막에 단정
//
// 여기서 하는 모든 조작은 사용자가 보는 표면(창·브라우저·IPC 설정)뿐이다.
// 스크린샷은 남기지 않는다. 실패 진단은 Playwright trace 가 담당한다(playwright.config.ts).
import { randomUUID } from 'node:crypto'
import { access, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { _electron as electron, expect as baseExpect, test as base } from '@playwright/test'
import type { ElectronApplication, Page } from '@playwright/test'
const APP_ENTRY = path.resolve(__dirname, '../../../out/main/index.js')
const MAIN_WINDOW_TIMEOUT_MS = 30_000
export interface MainWindowContext {
app: ElectronApplication
window: Page
/** 렌더러에서 예상치 못하게 찍힌 console.error (Electron 보안 경고/CSP/리소스 로드 실패는 제외) */
consoleErrors: string[]
/** 잡히지 않은 렌더러 예외 */
pageErrors: string[]
}
interface Options {
/** false 면 온보딩을 우회하지 않고 첫 실행 상태로 띄운다. */
onboardingCompleted: boolean
}
const IGNORED_CONSOLE_PATTERNS = [
'Electron Security Warning',
'Content Security Policy',
'Failed to load resource',
'favicon.ico',
'net::ERR_',
]
function isIgnoredConsoleError(text: string): boolean {
return IGNORED_CONSOLE_PATTERNS.some((pattern) => text.includes(pattern))
}
async function waitForMainWindow(app: ElectronApplication): Promise<Page> {
const deadline = Date.now() + MAIN_WINDOW_TIMEOUT_MS
while (Date.now() < deadline) {
for (const candidate of app.windows()) {
try {
const url = candidate.url()
if (url.includes('index.html') && !url.includes('popups/')) return candidate
} catch {
// 창이 아직 이동 중이다. 다음 폴링에서 다시 본다.
}
}
await new Promise((resolve) => setTimeout(resolve, 250))
}
throw new Error(
`메인 창이 ${MAIN_WINDOW_TIMEOUT_MS}ms 안에 나타나지 않았습니다. 열린 창: ${app
.windows()
.map((w) => {
try {
return w.url()
} catch {
return '<navigating>'
}
})
.join(', ')}`,
)
}
interface ConfigBridge {
config?: {
set(params: { key: string; value: unknown }): Promise<unknown>
}
}
async function applyConfigBypass(window: Page, onboardingCompleted: boolean): Promise<void> {
await window.evaluate(async (completed) => {
const bridge = (window as unknown as { electronAPI?: ConfigBridge }).electronAPI
if (!bridge?.config) {
throw new Error('electronAPI.config 가 없습니다. preload 브리지가 노출되지 않았습니다.')
}
await bridge.config.set({ key: 'onboardingCompleted', value: completed })
await bridge.config.set({ key: 'appUsageMode', value: 'online' })
await bridge.config.set({ key: 'llmBackend', value: 'online' })
}, onboardingCompleted)
await window.reload()
await window.waitForLoadState('domcontentloaded')
await baseExpect(window.getByRole('navigation')).toBeVisible({ timeout: 15_000 })
}
export const test = base.extend<Options & { mainWindow: MainWindowContext }>({
onboardingCompleted: [true, { option: true }],
mainWindow: async ({ onboardingCompleted }, use) => {
await access(APP_ENTRY).catch(() => {
throw new Error(
`데스크톱 E2E 는 빌드 산출물이 필요합니다: ${APP_ENTRY} 가 없습니다. ` +
'`npm run build --workspace=@d3ro/desktop` 를 먼저 실행하세요.',
)
})
const userDataDir = await mkdtemp(path.join(tmpdir(), `d3ro-e2e-${randomUUID()}-`))
const consoleErrors: string[] = []
const pageErrors: string[] = []
const app = await electron.launch({
args: [APP_ENTRY, '--disable-gpu', '--no-sandbox', `--user-data-dir=${userDataDir}`],
env: { ...process.env, NODE_ENV: 'test' },
})
try {
const window = await waitForMainWindow(app)
await window.waitForLoadState('domcontentloaded')
window.on('pageerror', (error) => pageErrors.push(error.message))
window.on('console', (message) => {
if (message.type() !== 'error') return
const text = message.text()
if (!isIgnoredConsoleError(text)) consoleErrors.push(text)
})
await applyConfigBypass(window, onboardingCompleted)
await use({ app, window, consoleErrors, pageErrors })
} finally {
await app.close().catch(() => undefined)
await rm(userDataDir, { recursive: true, force: true }).catch(() => undefined)
}
},
})
export { expect } from '@playwright/test'
/** 렌더러가 조용히 실패하지 않았음을 테스트 끝에서 확인한다. */
export function expectNoRuntimeErrors(context: MainWindowContext): void {
baseExpect(context.pageErrors, '잡히지 않은 렌더러 예외').toEqual([])
baseExpect(context.consoleErrors, '렌더러 console.error').toEqual([])
}
/** 사이드바 항목을 눌러 화면을 옮긴다. 현재 화면 표시(aria-current)까지 확인한다. */
export async function goToRoute(context: MainWindowContext, route: string): Promise<void> {
const button = context.window.getByRole('navigation').getByTestId(`nav-${route}`)
await button.click()
await baseExpect(button).toHaveAttribute('aria-current', 'page')
}