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):
Identity printer for string output.
Snapshot.custom Printer.string "log output" <|
\() -> formatLog entryProduces .txt files by default.
JSON pretty-printer with sorted keys and 2-space indentation.
Snapshot.json "user data" <|
\() -> User.encode userKeys 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.
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.userA 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.userThe 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.
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.
A printer converts a value of type
ato a String and specifies the file extension for syntax highlighting in diff tools.The extension is used to generate snapshot filenames like: