UNPKG

web-snaps

Version:

Browser automation with automatic snapshotting.

48 lines (47 loc) 1.87 kB
import { assert } from '@augment-vir/assert'; import { ensureErrorAndPrependMessage } from '@augment-vir/common'; import { convertTemplateToString } from 'element-vir'; import { JSDOM } from 'jsdom'; import { existsSync } from 'node:fs'; import { relative } from 'node:path'; /** * Load a saved {@link WebSnap} from the file system. * * @category Main */ export async function loadWebSnap(webFlow) { if (!webFlow.webSnapPaths) { throw new Error(`Cannot load WebSnap from WebFlow ${webFlow.flowKey}: no snapshot directory was defined.`); } /** Only used for error messages. */ const relativePath = relative(process.cwd(), webFlow.webSnapPaths.ts); if (!existsSync(webFlow.webSnapPaths.ts) && !existsSync(webFlow.webSnapPaths.js)) { throw new Error(`Missing snapshot file: ${relativePath}`); } try { /** Always import from `.js` (importing from `.ts` will fail). */ const webSnap = (await import(webFlow.webSnapPaths.js)).default; return webSnap; } catch (error) { throw ensureErrorAndPrependMessage(error, `Malformed snapshot file '${relativePath}': `); } } /** * Load a saved {@link WebSnap} phase snapshot from the file system for testing purposes. * * @category Main */ export async function loadPhaseSnapshot(webFlow, phaseName) { const webSnap = await loadWebSnap(webFlow); const phaseSnapshot = webSnap.phaseSnaps.find((snapshot) => snapshot.phaseName === phaseName); assert.isDefined(phaseSnapshot, `WebSnap '${webFlow.flowKey}' has no saved snapshot for phase '${phaseName}'`); const domString = convertTemplateToString(phaseSnapshot.pageHtml); return { domString: domString, /** This is a getter so that we don't construct `JSDOM` until necessary. */ get dom() { return new JSDOM(domString); }, }; }