MediumPro challengeJavaScriptTypeScript

Implement Snapshot Testing

TestingJavaScriptUtilities

Implement solve(op, ...args) for a minimal snapshot system:

OpArgsDescription
'serialize'(value)Returns a deterministic string representation of value (objects, arrays, primitives).
'save'(name, value)Stores the serialized snapshot under name. Returns 'saved'.
'match'(name, value)Compares serialized value to the stored snapshot. Returns { pass, diff }. diff is null on pass, or { expected, received } on fail.
'has'(name)Returns true if snapshot exists.
'delete'(name)Removes snapshot. Returns true if it existed.

Serialization rules:

  • Primitives: JSON.stringify(value)
  • Arrays: [ item1, item2 ] (one item per line, indented 2 spaces)
  • Objects: { key: value } (sorted keys, indented 2 spaces)
solve('save', 'user', { name: 'Alice', age: 30 })
solve('match', 'user', { name: 'Alice', age: 30 })   // { pass: true, diff: null }
solve('match', 'user', { name: 'Bob', age: 30 })
// { pass: false, diff: { expected: '...Alice...', received: '...Bob...' } }

Sample tests

Test #1serialize primitive number
Input: ["serialize",42]
Output: "42"
Test #2serialize string
Input: ["serialize","hello"]
Output: "\"hello\""
Test #3save returns "saved"
Input: ["save","user",{"age":30,"name":"Alice"}]
Output: "saved"
Test #4match passes even with different key order
Input: ["match","user",{"age":30,"name":"Alice"}]
Output: {"diff":null,"pass":true}
Test #5match fails and returns diff
Input: ["match","user",{"age":30,"name":"Bob"}]
Output: {"diff":{"expected":"{\n \"age\": 30,\n \"name\": \"Alice\"\n}","received":"{\n \"age\": 30,\n \"name\": \"Bob\"\n}"},"pass":false}