Created
August 11, 2021 08:06
-
-
Save hasparus/2edc30f4d5cbc9707059581414b20d5d to your computer and use it in GitHub Desktop.
When you rename a test file the snapshot name changes and the old snapshot is declared obsolete. Thankfully, as Jest snapshots are JS files exporting a bunch of strings, we can compare them with a simple script instead of going through them by hand.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function requireSnapshots(paths: string[]) { | |
const map = new Map<string, string>() | |
for (const path of paths) { | |
const module = require(path) | |
for (const name of Object.keys(module)) { | |
if (map.has(name)) { | |
throw new Error(`Conflict on snapshot "${name}" in ${paths}`) | |
} | |
map.set(name, module[name]) | |
} | |
} | |
return map | |
} | |
function findDifferences( | |
oldMap: Map<string, string>, | |
newMap: Map<string, string> | |
) { | |
const removedSnapshots = Array.from(oldMap.keys()).filter( | |
(name) => !newMap.has(name) | |
) | |
const addedSnapshots = Array.from(newMap.keys()).filter( | |
(name) => !oldMap.has(name) | |
) | |
const commonKeys = new Set([ | |
...Array.from(oldMap.keys()), | |
...Array.from(newMap.keys()), | |
]) | |
const results = Array.from(commonKeys).map((key) => { | |
const oldValue = oldMap.get(key) | |
const newValue = newMap.get(key) | |
if (oldValue !== newValue) { | |
return { | |
status: 'difference', | |
key, | |
oldValue, | |
newValue, | |
} | |
} else { | |
return { | |
status: 'same', | |
key, | |
} | |
} | |
}) | |
return { | |
removedSnapshots, | |
addedSnapshots, | |
results, | |
} | |
} | |
const newSnapshots = requireSnapshots([ | |
'./Box.spec.tsx.snap', | |
'./Buttons.spec.tsx.snap', | |
'./Grid.spec.tsx.snap', | |
'./index.tsx.snap', | |
]) | |
const oldSnapshots = requireSnapshots(['./index.js.snap']) | |
console.log(findDifferences(oldSnapshots, newSnapshots)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment