Skip to content

Test Runner: custom parser for snapshot #57830

Open
@axetroy

Description

@axetroy

What is the problem this feature will solve?

Currently, snapshots have a special format and appear to be cjs modules

It is very convenient for snapshot parsing, but it is not suitable for human reading. It does not highlight.

I would like to have a way to customize the snapshot, since I prefer .snapshot.md to .snapshot format.

What is the feature you are proposing to solve the problem?

Add a custom parse to custom snapshot's format.

Definition:

declare module "snapshot" {
  /**
   * Sets the snapshot parser to be used for parsing and taking snapshots.
   * @param parser
   */
  export function setSnapshotParser(parser: SnapshotParser): void;

  /**
   * Interface representing a snapshot parser.
   */
  interface SnapshotParser {
    /**
     * Resolve the path to the snapshot file.
     * @param filePath
     */
    resolve(filePath: string): string;

    /**
     * Parses a snapshot file and returns its contents as a Map.
     * @param snapshotFilePath - The path to the snapshot file.
     * @returns The parsed snapshot as a Map.
     */
    parse(snapshotFilePath: string): Map<string, string>;

    /**
     * Takes a snapshot of the given value and saves it to the specified file.
     * @param value
     */
    snapshot(value: unknown): void;
  }
}

Usage:

In this example, we use custom markdown as a snapshot

snapshot.setSnapshotParser({
	// ✅ Use the markdown format for snapshots
	resolve: (filePath: string) => {
		return filePath + '.snapshot.md'
	},
	// ✅ Parse the snapshot file and return its contents as a Map
	parse: (snapshotFilePath: string) => {
		// Implement your parsing logic here
		return new Map<string, string>()
	},
	// ✅ Take a snapshot of the given value and save it to the specified file
	snapshot: (value: unknown) => {
		// Implement your snapshot logic here
	}
})

What alternatives have you considered?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues that request new features to be added to Node.js.test_runnerIssues and PRs related to the test runner subsystem.

    Type

    No type

    Projects

    Status

    Awaiting Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions