import { NAME } from '../shared/constants.ts' import type { ComparisonMethod, SnapshotMeta } from '../shared/types.ts' import { ctx } from './ctx.ts' type Suite = { meta: Record; suite?: Suite | undefined } export type MetaTask = | { file?: { meta: Record } | undefined suite?: Suite | undefined meta: Record } | undefined export function enableAuto() { ctx.autoEnabled = true } /** * Set the snapshot options for auto snapshot. * * ```ts * beforeAll((suite) => setAutoSnapshotOptions(suite, ...)) * beforeEach(({ task }) => setAutoSnapshotOptions(task, ...)) * * it('...', ({ task }) => { * setAutoSnapshotOptions(task, ...) * }) * ``` * * @param task Optional. Suite or task to set the options. * If not provided, it will set the options for the current test. */ export function setAutoSnapshotOptions( task: MetaTask, meta: SnapshotMeta | boolean, ): void export function setAutoSnapshotOptions(meta: SnapshotMeta | boolean): void export function setAutoSnapshotOptions( ...args: [task: MetaTask, meta: SnapshotMeta | boolean] | [meta: SnapshotMeta | boolean] ): void { const [task, meta] = parseArgs(args) if (task) task.meta[NAME] = { ...task.meta[NAME], ...meta, } } function parseArgs( args: [task: MetaTask, meta: SnapshotMeta | boolean] | [meta: boolean | SnapshotMeta], ): [MetaTask | undefined, SnapshotMeta] { return args.length === 1 ? [ctx.getCurrentTest() ?? (ctx.getCurrentSuite()?.tasks?.[0] as any)?.file, parseMeta(args[0])] : [args[0], parseMeta(args[1])] } function parseMeta(meta: boolean | SnapshotMeta): SnapshotMeta { return typeof meta === 'boolean' ? ({ enable: meta } as any) : { enable: true, ...meta } } export function extractAutoSnapshotOptions = SnapshotMeta>( task: MetaTask, ): M | undefined { if (!task) return const list: any[] = [] let current = task while (current?.suite) { list.unshift(current.suite.meta) current = current.suite } list.unshift(task.file?.meta) list.push(task.meta) return list.reduce( (acc, cur) => { const meta = cur?.[NAME] return meta ? Object.assign({}, acc, meta) : acc }, { enable: ctx.autoEnabled }, ) }