e-lado
Version:
[](https://circleci.com/gh/sharetribe/sharetribe/tree/master) [](https://gemnasium.com/sharetribe/shar
105 lines (82 loc) • 2.7 kB
JavaScript
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
;
const createDirectory = require('jest-util').createDirectory;
const fileExists = require('jest-file-exists');
const path = require('path');
const prettyFormat = require('pretty-format');
const fs = require('fs');
const naturalCompare = require('natural-compare');
const getPlugins = require('./plugins').getPlugins;
const SNAPSHOT_EXTENSION = 'snap';
const testNameToKey = (testName, count) =>
testName + ' ' + count;
const keyToTestName = key => {
if (!/ \d+$/.test(key)) {
throw new Error('Snapshot keys must end with a number.');
}
return key.replace(/ \d+$/, '');
};
const getSnapshotPath = testPath => path.join(
path.join(path.dirname(testPath), '__snapshots__'),
path.basename(testPath) + '.' + SNAPSHOT_EXTENSION);
const getSnapshotData = snapshotPath => {
const data = Object.create(null);
if (fileExists(snapshotPath)) {
try {
delete require.cache[require.resolve(snapshotPath)];
/* eslint-disable no-useless-call */
Object.assign(data, require.call(null, snapshotPath));
/* eslint-enable no-useless-call */
} catch (e) {}
}
return data;
};
// Extra line breaks at the beginning and at the end of the snapshot are useful
// to make the content of the snapshot easier to read
const addExtraLineBreaks =
string => string.includes('\n') ? `\n${ string }\n` : string;
const serialize = data => {
return addExtraLineBreaks(prettyFormat(data, {
escapeRegex: true,
plugins: getPlugins(),
printFunctionName: false }));
};
const escape = string => string.replace(/(\`|\${)/g, '\\$1');
const unescape = string => string.replace(/\\(\"|\\|\'|\${)/g, '$1');
const ensureDirectoryExists = filePath => {
try {
createDirectory(path.join(path.dirname(filePath)));
} catch (e) {}
};
const normalizeNewlines =
string => string.replace(/\r\n/g, '\n');
const saveSnapshotFile = (
snapshotData,
snapshotPath) =>
{
const snapshots = Object.keys(snapshotData).sort(naturalCompare).
map(key =>
'exports[`' + escape(key) + '`] = `' +
normalizeNewlines(escape(snapshotData[key])) + '`;');
ensureDirectoryExists(snapshotPath);
fs.writeFileSync(snapshotPath, snapshots.join('\n\n') + '\n');
};
module.exports = {
SNAPSHOT_EXTENSION,
ensureDirectoryExists,
escape,
getSnapshotData,
getSnapshotPath,
keyToTestName,
saveSnapshotFile,
serialize,
testNameToKey,
unescape };