Last active
April 16, 2024 21:50
-
-
Save maksimr/2107886f60917c1932cf1286b6c01b38 to your computer and use it in GitHub Desktop.
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
const fs = require('node:fs/promises'); | |
const assert = require('node:assert/strict'); | |
const windowNewlineRegexp = /\r/g; | |
function replaceWindowsLineEndings(str) { | |
return str.replace(windowNewlineRegexp, ''); | |
} | |
function getSnapshotPath(filename) { | |
return filename + '.snap'; | |
} | |
async function assertSnapshot(actual, filename = process.argv[1]) { | |
const snapshot = getSnapshotPath(filename); | |
if (process.env.NODE_REGENERATE_SNAPSHOTS) { | |
await fs.writeFile(snapshot, actual); | |
console.log(`Snapshot regenerated: ${snapshot}`); | |
} else { | |
let expected; | |
try { | |
expected = await fs.readFile(snapshot, 'utf8'); | |
} catch (e) { | |
if (e.code === 'ENOENT') { | |
await fs.writeFile(snapshot, actual); | |
console.log(`Snapshot created: ${snapshot}`); | |
return; | |
} | |
throw e; | |
} | |
assert.strictEqual(actual, replaceWindowsLineEndings(expected)); | |
} | |
} | |
module.exports = { | |
assertSnapshot | |
}; |
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
const assert = require('assert'); | |
const { SnapshotState, toMatchSnapshot } = require('jest-snapshot'); | |
function getSnapshotPath(filename) { | |
return filename + '.snap'; | |
} | |
/** | |
* @param {any} actual | |
* @param {{name: string; testPath?: string}} testContext | |
*/ | |
async function assertSnapshot(actual, { name: currentTestName, testPath = process.argv[1] }) { | |
const snapshotPath = getSnapshotPath(testPath); | |
const NODE_UPDATE_SNAPSHOT = process.env.NODE_UPDATE_SNAPSHOT || 'new'; | |
const snapshotState = new SnapshotState(snapshotPath, { | |
updateSnapshot: /^(all|new|none)$/.test(NODE_UPDATE_SNAPSHOT) ? NODE_UPDATE_SNAPSHOT : 'all' | |
}); | |
const result = ({ | |
snapshotState, | |
currentTestName, | |
toMatchSnapshot | |
}).toMatchSnapshot(actual); | |
snapshotState.save(); | |
assert(result.pass, result.pass ? '' : result.message()); | |
} | |
module.exports = { | |
assertSnapshot: assertSnapshot | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment