codejump
MediumPro challengePythonJavaScriptTypeScript

Implement Snapshot Testing

TestingUtilities

A snapshot test serializes a value, stores the string, and fails later if the serialization changes.

solve(ops) runs a list of operations against an empty snapshot store and returns their results:

OpResult
['serialize', value]the value's snapshot string (see format below)
['save', name, value]'saved' — stores (or overwrites) the snapshot name
['match', name, value]{ pass: true, diff: null } if value serializes to the stored snapshot, else { pass: false, diff: { expected, received } } (expected is null when no snapshot exists)
['has', name]whether a snapshot exists
['delete', name]true if a snapshot was deleted, false if there was none

Format

  • Primitives (numbers, strings, booleans, null) are serialized like JSON.stringify — 42, "hello", true, null.
  • Empty arrays / objects are [] / {}.
  • Otherwise one item per line, indented by 2 spaces per level; object keys are sorted and written as "key": value:
{
  "a": null,
  "b": [
    1,
    2
  ]
}

Sample tests

Test #1serialize a number
Input: [[["serialize",42]]]
Output: ["42"]
Test #2serialize a string
Input: [[["serialize","hello"]]]
Output: ["\"hello\""]
Test #3nested value, sorted keys
Input: [[["serialize",{"a":null,"b":[1,2]}]]]
Output: ["{\n \"a\": null,\n \"b\": [\n 1,\n 2\n ]\n}"]
Test #4match ignores key order
Input: [[["save","user",{"age":30,"name":"Alice"}],["match","user",{"age":30,"name":"Alice"}]]]
Output: ["saved",{"diff":null,"pass":true}]
Test #5mismatch returns a diff
Input: [[["save","user",{"age":30,"name":"Alice"}],["match","user",{"age":30,"name":"Bob"}]]]
Output: ["saved",{"diff":{"expected":"{\n \"age\": 30,\n \"name\": \"Alice\"\n}","received":"{\n \"age\": 30,\n \"name\": \"Bob\"\n}"},"pass":false}]