dillonkearns/elm-snapshot/1.1.1

Snapshot.Printer

Printers convert domain objects to strings for snapshot comparison.

Every snapshot test has a printer (even if it's just identity). The printer's job is to create a human-readable, diffable representation.

Best practices (Emily Bache):

  • Keep lines short for easy diff viewing
  • JSON can be tricky - prefer pretty-printing
  • Include inputs in output for context
  • Change printers in separate commits from logic changes

Definition

type alias Printer a =
{ extension : String
, print : a -> String
}

A printer converts a value of type a to a String and specifies the file extension for syntax highlighting in diff tools.

The extension is used to generate snapshot filenames like:

test_name.approved.json


test_name.received.txt

Common Printers

string : Printer String

Identity printer for string output.

Snapshot.custom Printer.string "log output" <|
    \() -> formatLog entry

Produces .txt files by default.

json : Printer Value

JSON pretty-printer with sorted keys and 2-space indentation.

Snapshot.json "user data" <|
    \() -> User.encode user

Keys are sorted alphabetically at all nesting levels for deterministic output. This matches the behavior of Go's json.Marshal and Jest's pretty-format - the modern consensus for testing tools.

Uses 2-space indentation, which is the most common convention for JSON and produces readable diffs with reasonable line lengths.

Produces .json files for syntax highlighting in diff tools.

elm : (a -> String) -> Printer a

Pretty-prints any Elm value using elm-format style. This requires Debug.toString to be passed as the first argument.

Since published packages cannot use Debug.toString directly, you must pass it in as the first argument:

Snapshot.custom (Printer.elm Debug.toString) "user model" <|
    \() -> model.user

A common pattern is to create a helper in your test file:

elmPrinter : Printer a
elmPrinter =
    Printer.elm Debug.toString


-- Then use it in your tests:
Snapshot.custom elmPrinter "user model" <|
    \() -> model.user

The output is formatted as valid Elm syntax, making diffs easy to read.

Produces .elm files for syntax highlighting in diff tools.

Dependencies: This printer relies on kraklin/elm-debug-parser and lue-bird/elm-syntax-format to parse and format the debug output.

Customization

withExtension : String -> Printer a -> Printer a

Change the file extension of a printer.

xmlPrinter : Printer String
xmlPrinter =
    Printer.string
        |> Printer.withExtension "xml"

Useful when the content type doesn't match the default extension.