Skip to content

Instantly share code, notes, and snippets.

@maksimr
Last active April 16, 2024 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maksimr/2107886f60917c1932cf1286b6c01b38 to your computer and use it in GitHub Desktop.
Save maksimr/2107886f60917c1932cf1286b6c01b38 to your computer and use it in GitHub Desktop.
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
};
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