UNPKG

histoire

Version:

A fast story book powered by Vite

182 lines (181 loc) • 10.3 kB
import { basename } from 'node:path'; import { performance } from 'node:perf_hooks'; import { HistoireSdkError } from '@histoire/protocol'; import fs from 'fs-extra'; import pc from 'picocolors'; import { scanMarkdownFiles } from '../markdown.js'; import { findAllStories } from '../stories.js'; import { collectStoriesBrowser } from '../story-collection/index.js'; import { loadProjectVitest } from '../util/project-vitest.js'; import { getRunTempDir } from '../util/temp-paths.js'; import { throwIfTestAborted } from '../util/test-abort.js'; import { getRunStallTimeout, getTestMaxWorkers } from '../util/test-timeouts.js'; import { runVitestAttempts } from '../util/vitest-run.js'; import { createVitestRunActivity } from '../util/vitest-start-timeout.js'; import { debugVitestBrowserLifecycle } from '../vitest-browser-config/index.js'; import { reportStuckTestRun, warnAboutMissingTestModules } from './diagnostics.js'; import { ensureBrowserTestDepsInstalled, ensureProjectVitest } from './preflight.js'; import { progressReporterOptions } from './progress-reporter.js'; import { generateSpecFiles } from './spec-files.js'; import { createEmptyTestSummary, summarizeResults } from './summary.js'; import { formatNoMatchingTestsWarning, getTargetStoryFiles, selectSpecFiles } from './targeting.js'; import { assertTargetedStoriesCollected, warnAboutUncollectedStories, withUncollectedStories } from './uncollected.js'; import { getTestVitestConfig } from './vitest-config.js'; /** Label used in the cleanup diagnostics of a test run. */ const CLEANUP_LABEL = 'Histoire tests'; /** * Runs the Histoire tests of a project (or of a single story/variant) in a real * browser through the project's own Vitest. * @param ctx The histoire context. * @param options Run options (see {@link RunHistoireTestsOptions}). */ export async function runHistoireTests(ctx, options = {}) { if (options.isolate) { const { runIsolatedHistoireTests } = await import('./isolated.js'); return runIsolatedHistoireTests(ctx, options); } // Each run owns its spec directory: a shared one emptied at the start of the // run would delete the specs of any concurrent run in the same project. const specRoot = getRunTempDir(ctx.root, 'tests'); try { const summary = await runTests(ctx, options, specRoot); if (!options.strictTarget) return summary; return { ...summary, execution: { runId: basename(specRoot), mode: 'server', ...(options.storyId ? { target: { storyId: options.storyId, variantId: options.variantId ?? null } } : {}) } }; } finally { // Remove the generated specs on every path, including failures. await fs.remove(specRoot).catch(() => { }); } } /** * Collects the targeted stories, generates their specs and runs them. * @param ctx The histoire context. * @param options Run options (see {@link RunHistoireTestsOptions}). * @param specRoot Directory owned by this run, where the specs are generated. */ async function runTests(ctx, options, specRoot) { throwIfTestAborted(options.signal); const startTime = performance.now(); const hasExplicitSelection = Boolean(options.storyId || options.variantId); ensureProjectVitest(ctx); // Checked here rather than in the CLI command: a run triggered from the dev // UI needs the same actionable message, and both resolve from the context // root instead of whatever directory the process happens to run in. await ensureBrowserTestDepsInstalled(ctx.root); throwIfTestAborted(options.signal); if (!options.skipStoryScan) { await findAllStories(ctx); await scanMarkdownFiles(ctx); } throwIfTestAborted(options.signal); const targetStoryFiles = options.strictTarget && !options.skipStoryScan ? ctx.storyFiles : getTargetStoryFiles(ctx, options); // `onTest` is registered at runtime at any call depth (shared helpers, // renamed imports…), so only executing the story reveals whether it defines // tests: the browser collection is the sole source of eligibility. const collection = targetStoryFiles.length ? await collectStoriesBrowser(ctx, { storyFiles: targetStoryFiles, // The dev server keeps collecting into its own story file objects // while this run is in flight — never write back into them. applyToContext: !options.skipStoryScan, // Discovering eligibility means collecting stories the user never asked // about: one broken unrelated story must not abort their test run. tolerateStoryFailures: true, onProgress: options.onRunProgress && (progress => options.onRunProgress({ phase: 'collect', ...progress })), signal: options.signal, strictCleanup: options.strictCleanup, }) : { files: [], failures: [] }; throwIfTestAborted(options.signal); assertTargetedStoriesCollected(collection.failures, targetStoryFiles, options); if (options.strictTarget && options.storyId) { const matches = collection.files.filter(file => file.storyFile.story?.id === options.storyId); if (!matches.length) throw new HistoireSdkError(collection.failures.length ? 'COLLECTION_FAILED' : 'STORY_NOT_FOUND', 'Requested story could not be resolved'); if (matches.length > 1) throw new HistoireSdkError('STORY_AMBIGUOUS', 'Requested story ID is ambiguous'); if (options.variantId && !matches[0].storyFile.story.variants.some(variant => variant.id === options.variantId)) throw new HistoireSdkError('VARIANT_NOT_FOUND', 'Requested variant does not exist'); } warnAboutUncollectedStories(collection.failures); // Vanilla metadata collection never mounts its app, so absence of registrations // cannot prove that configured setup hooks contribute no tests. Let variant // collection inspect these candidates, retaining fast omission for other stories. const hasSetup = Boolean(ctx.config.setupFile || ctx.config.setupCode?.length); const specFiles = await generateSpecFiles(collection.files.filter(collected => collected.hasTests || (hasSetup && collected.storyFile.supportPluginId === 'vanilla')).map(collected => collected.storyFile), specRoot); const selectedSpecFiles = selectSpecFiles(specFiles, options); if (hasExplicitSelection && selectedSpecFiles.length === 0) { console.warn(pc.yellow(formatNoMatchingTestsWarning(options))); return withUncollectedStories(createEmptyTestSummary(), collection.failures); } throwIfTestAborted(options.signal); const { parseCLI } = await loadProjectVitest(ctx.root); const { filter, options: vitestOptions } = parseCLI(['vitest', ...(options.rawVitestArgs ?? [])], { allowUnknownOptions: true, }); const include = selectedSpecFiles.map(item => item.path); if (include.length === 0) { return withUncollectedStories(createEmptyTestSummary(), collection.failures); } if (vitestOptions.watch) { console.warn(pc.yellow('`histoire test` does not support watch mode yet — running once.')); } const summary = await runVitestAttempts({ label: CLEANUP_LABEL, root: ctx.root, signal: options.signal, strictCleanup: options.strictCleanup, maxRetries: options.maxRetries, retryMessage: 'Retrying Histoire tests after Vitest browser optimizer reload', // Rebuilt per attempt: the config carries live plugin instances bound to // the Vite server of the attempt that created them. setup: async () => { const runtimeConfig = await getTestVitestConfig(ctx, include); debugVitestBrowserLifecycle('test:starting vitest...'); // Every finished spec restarts the stall timeout and reaches progress listeners (dev UI runs). const activity = createVitestRunActivity(); const onSpecProgress = (progress) => { activity.touch(); options.onRunProgress?.({ phase: 'run', ...progress }); }; return { vitestOptions: { passWithNoTests: true, include, ...runtimeConfig.vitestOptions, ...vitestOptions, ...progressReporterOptions(vitestOptions.reporters, include.length, onSpecProgress), // Keep raw Vitest flags useful while retaining Histoire's configured // concurrency ceiling for generated browser specs. maxWorkers: getTestMaxWorkers(ctx), // Invariants last so raw vitest args cannot override them: the run // must use Histoire's generated config (a user `--config` module // would replace it), and watch mode is unsupported — the runner is // torn down right after the first pass either way. config: false, run: true, watch: false, }, viteConfig: runtimeConfig.viteConfig, browserProjectOptions: runtimeConfig.browserProjectOptions, prepareBrowser: true, filter, timeoutMs: getRunStallTimeout(ctx), activity, timeoutMessage: `Histoire test run timed out: no variant finished for ${Math.round(getRunStallTimeout(ctx) / 1000)}s (test.runStallTimeout).`, onTimeout: reportStuckTestRun, context: undefined, }; }, read: (vitest) => { debugVitestBrowserLifecycle('test:vitest.start() resolved'); const testModules = vitest.state.getTestModules(); warnAboutMissingTestModules(testModules, include); // Errors outside test cases fail their variant (or the run) without discarding other results. return withUncollectedStories(summarizeResults(testModules, specFiles, vitest.state.getUnhandledErrors()), collection.failures); }, }); console.log(pc.blue(`Histoire tests finished in ${Math.round(performance.now() - startTime)}ms`)); return summary; }