Skip to content

Instantly share code, notes, and snippets.

@LucaColonnello
Created February 6, 2018 16:10
Show Gist options
  • Save LucaColonnello/86497ab685c24c5497a027b4a7f0801d to your computer and use it in GitHub Desktop.
Save LucaColonnello/86497ab685c24c5497a027b4a7f0801d to your computer and use it in GitHub Desktop.
Mocha snapshot test
const { writeFileSync } = require('fs');
const prettyFormat = require('pretty-format');
const reactTestPlugin = require('pretty-format/plugins/ReactTestComponent');
const reactElementPlugin = require('pretty-format/plugins/ReactElement');
let globalForceUpdate = false;
if (process.argv.includes('--snapshots-update')) {
globalForceUpdate = true;
}
const serialize = (key, content) => {
const escapedContent = content.replace(/\\/g, '\\\\')
.replace(/`/g, '\\`')
.replace(/\$/g, '\\$')
.replace(/^\n|\n$/g, '');
return `exports[\`${key}\`] = \`\n${escapedContent}\n\`;\n`;
};
const serializeFile = fileContents => {
const linterDisable = '/* eslint-disable */';
const contents = Object.keys(fileContents).map(key => {
return serialize(key, fileContents[key]);
}).join('\n');
return `${linterDisable}\n${contents}`;
};
const deserialize = content => {
return content.replace(/^\n|\n$/g, '');
};
const toMatchSnapshot = ({ fileName, name, forceUpdate = false }, content) => {
if (!fileName) {
throw new Error('toMatchSnapshot: fileName is required');
}
if (!name) {
throw new Error('toMatchSnapshot: name is required');
}
if (!content) {
throw new Error('toMatchSnapshot: content is required');
}
const prettyContent = prettyFormat(content, {
plugins: [reactTestPlugin, reactElementPlugin]
});
let sourceContent;
let toBeSaved;
// try to load the file
try {
const jsonSnapshotSource = require(fileName);
if (!jsonSnapshotSource[name] || forceUpdate || globalForceUpdate) {
sourceContent = jsonSnapshotSource[name] = prettyContent;
toBeSaved = serializeFile(jsonSnapshotSource);
} else {
sourceContent = jsonSnapshotSource[name];
}
} catch (e) {
toBeSaved = serializeFile({
[name]: prettyContent
});
sourceContent = prettyContent;
}
// save in JSON format
if (toBeSaved) {
writeFileSync(fileName, toBeSaved);
}
const message = `Received content doesn't match the snapshot in ${fileName.replace(process.cwd(), '')}`;
assert.equal(deserialize(sourceContent), prettyContent, message);
};
module.exports = toMatchSnapshot;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment