histoire
Version:
A fast story book powered by Vite
64 lines (55 loc) • 2.46 kB
JavaScript
import { resolveBrowserRuntimeEntry } from '../util/resolve-browser-runtime.js';
import { getStoryCollectTimeout } from '../util/test-timeouts.js';
import { buildStoryModuleLoaders, getRuntimeStoryFiles } from './preview-runtime/index.js';
import { generatedKnownEmptySetupProbe } from './variant-test-session/setup-hooks.js';
import { VITEST_DYNAMIC_IMPORT_SNIPPET } from './vitest-runner-bootstrap.js';
/**
* Emits the browser test harness module: the story metadata plus one dynamic
* module loader per story file, wrapped in a variant test session.
*
* Kept free of module resolution (which needs a real install layout) so the
* generated source can be exercised on its own.
*/
export function buildTestHarnessSource({ variantTestSessionId, files, mountTimeoutMs }) {
// The harness runs one Vitest pass per story: no hot update can invalidate a
// module mid-run, so the plain (bundler-analyzable) loaders are enough.
const loaders = buildStoryModuleLoaders(files);
return `
import 'virtual:$histoire-theme'
import { createVariantTestSession, getVitestBrowserMountCleanups, hasVanillaSetupHooks, releaseFinishedSpecs } from ${JSON.stringify(variantTestSessionId)}
// Evaluated once per spec file, each in a fresh iframe: free the documents of the previous ones.
releaseFinishedSpecs()
const files = ${JSON.stringify(files)}
const moduleLoaders = {
${loaders.join(',\n ')}
}
globalThis.vi ??= {}
globalThis.vitest ??= globalThis.vi
${VITEST_DYNAMIC_IMPORT_SNIPPET}
${generatedKnownEmptySetupProbe()}
const variantTestSession = createVariantTestSession({
files,
mountTimeoutMs: ${mountTimeoutMs},
moduleLoaders,
runWithDynamicImport: runWithVitestDynamicImport,
canSkipKnownEmptyCollection,
})
export async function collectVariantTests(storyId, variantId) {
return await variantTestSession.collectVariantTests(storyId, variantId)
}
export async function prepareVariantTestRun(storyId, variantId) {
return await variantTestSession.prepareVariantTestRun(storyId, variantId, getVitestBrowserMountCleanups())
}
`;
}
/**
* Virtual module factory for `virtual:$histoire-test-harness`.
* @param ctx Histoire context holding the collected story files.
*/
export function testHarness(ctx) {
return buildTestHarnessSource({
variantTestSessionId: resolveBrowserRuntimeEntry('variant-test-session'),
files: getRuntimeStoryFiles(ctx),
mountTimeoutMs: getStoryCollectTimeout(ctx),
});
}