|
| 1 | +import { type Page, launch } from 'puppeteer'; |
| 2 | +import { execAndWaitForOutputToMatch, killAllProcesses } from './process'; |
| 3 | + |
| 4 | +export interface E2eTestOptions { |
| 5 | + project?: string; |
| 6 | + configuration?: string; |
| 7 | + baseUrl?: string; |
| 8 | + checkFn?: (page: Page) => Promise<void>; |
| 9 | +} |
| 10 | + |
| 11 | +export async function runE2eTest(options: E2eTestOptions = {}) { |
| 12 | + let url = options.baseUrl; |
| 13 | + let hasStartedServer = false; |
| 14 | + |
| 15 | + try { |
| 16 | + if (!url) { |
| 17 | + // Start serving |
| 18 | + const match = /open your browser on (http:\/\/localhost:\d+\/)/; |
| 19 | + const serveArgs = ['serve', '--port=0']; |
| 20 | + if (options.project) { |
| 21 | + serveArgs.push(options.project); |
| 22 | + } |
| 23 | + if (options.configuration) { |
| 24 | + serveArgs.push(`--configuration=${options.configuration}`); |
| 25 | + } |
| 26 | + |
| 27 | + const { stdout } = await execAndWaitForOutputToMatch('ng', serveArgs, match); |
| 28 | + url = stdout.match(match)?.[1]; |
| 29 | + if (!url) { |
| 30 | + throw new Error('Could not find serving URL'); |
| 31 | + } |
| 32 | + hasStartedServer = true; |
| 33 | + } |
| 34 | + |
| 35 | + const browser = await launch({ executablePath: process.env['CHROME_BIN'], headless: true }); |
| 36 | + try { |
| 37 | + const page = await browser.newPage(); |
| 38 | + |
| 39 | + // Capture errors |
| 40 | + const errors: string[] = []; |
| 41 | + page.on('console', (msg) => { |
| 42 | + if (msg.type() === 'error') { |
| 43 | + errors.push(msg.text()); |
| 44 | + } |
| 45 | + }); |
| 46 | + page.on('pageerror', (err) => { |
| 47 | + errors.push(err.toString()); |
| 48 | + }); |
| 49 | + |
| 50 | + await page.goto(url); |
| 51 | + |
| 52 | + if (options.checkFn) { |
| 53 | + await options.checkFn(page); |
| 54 | + } else { |
| 55 | + // Default check: verify app-root exists |
| 56 | + await page.waitForSelector('app-root'); |
| 57 | + } |
| 58 | + |
| 59 | + if (errors.length > 0) { |
| 60 | + throw new Error(`Browser console errors detected:\n${errors.join('\n')}`); |
| 61 | + } |
| 62 | + } finally { |
| 63 | + await browser.close(); |
| 64 | + } |
| 65 | + } finally { |
| 66 | + if (hasStartedServer) { |
| 67 | + await killAllProcesses(); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments