Change endpoint from persons to people

This commit is contained in:
xfarrow
2025-03-23 21:00:08 +01:00
parent 4ae263662c
commit d005193f63
7158 changed files with 700476 additions and 735 deletions

View File

@ -0,0 +1,421 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.saveInlineSnapshots = saveInlineSnapshots;
var path = _interopRequireWildcard(require('path'));
var _util = require('util');
var fs = _interopRequireWildcard(require('graceful-fs'));
var _semver = _interopRequireDefault(require('semver'));
var _utils = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var jestWriteFile =
globalThis[Symbol.for('jest-native-write-file')] || fs.writeFileSync;
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var jestReadFile =
globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// prettier-ignore
const generate = // @ts-expect-error requireOutside Babel transform
require(require.resolve('@babel/generator', {
[(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for('jest-resolve-outside-vm-option')]: true
})).default;
const {
isAwaitExpression,
templateElement,
templateLiteral,
traverse,
traverseFast
} = require(require.resolve('@babel/types', { // @ts-expect-error requireOutside Babel transform
[(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for(
'jest-resolve-outside-vm-option'
)]: true
}));
// @ts-expect-error requireOutside Babel transform
const {parseSync} = require(require.resolve('@babel/core', {
[(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for(
'jest-resolve-outside-vm-option'
)]: true
}));
function saveInlineSnapshots(snapshots, rootDir, prettierPath) {
let prettier = null;
if (prettierPath) {
try {
// @ts-expect-error requireOutside Babel transform
prettier = require(require.resolve(prettierPath, {
[(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for(
'jest-resolve-outside-vm-option'
)]: true
}));
if (_semver.default.gte(prettier.version, '3.0.0')) {
throw new Error(
'Jest: Inline Snapshots are not supported when using Prettier 3.0.0 or above.\nSee https://jestjs.io/docs/configuration/#prettierpath-string for alternatives.'
);
}
} catch (error) {
if (!_util.types.isNativeError(error)) {
throw error;
}
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
}
}
const snapshotsByFile = groupSnapshotsByFile(snapshots);
for (const sourceFilePath of Object.keys(snapshotsByFile)) {
saveSnapshotsForFile(
snapshotsByFile[sourceFilePath],
sourceFilePath,
rootDir,
prettier && _semver.default.gte(prettier.version, '1.5.0')
? prettier
: undefined
);
}
}
const saveSnapshotsForFile = (snapshots, sourceFilePath, rootDir, prettier) => {
const sourceFile = jestReadFile(sourceFilePath, 'utf8');
// TypeScript projects may not have a babel config; make sure they can be parsed anyway.
const presets = [require.resolve('babel-preset-current-node-syntax')];
const plugins = [];
if (/\.([cm]?ts|tsx)$/.test(sourceFilePath)) {
plugins.push([
require.resolve('@babel/plugin-syntax-typescript'),
{
isTSX: sourceFilePath.endsWith('x')
},
// unique name to make sure Babel does not complain about a possible duplicate plugin.
'TypeScript syntax plugin added by Jest snapshot'
]);
}
// Record the matcher names seen during traversal and pass them down one
// by one to formatting parser.
const snapshotMatcherNames = [];
let ast = null;
try {
ast = parseSync(sourceFile, {
filename: sourceFilePath,
plugins,
presets,
root: rootDir
});
} catch (error) {
// attempt to recover from missing jsx plugin
if (error.message.includes('@babel/plugin-syntax-jsx')) {
try {
const jsxSyntaxPlugin = [
require.resolve('@babel/plugin-syntax-jsx'),
{},
// unique name to make sure Babel does not complain about a possible duplicate plugin.
'JSX syntax plugin added by Jest snapshot'
];
ast = parseSync(sourceFile, {
filename: sourceFilePath,
plugins: [...plugins, jsxSyntaxPlugin],
presets,
root: rootDir
});
} catch {
throw error;
}
} else {
throw error;
}
}
if (!ast) {
throw new Error(`jest-snapshot: Failed to parse ${sourceFilePath}`);
}
traverseAst(snapshots, ast, snapshotMatcherNames);
// substitute in the snapshots in reverse order, so slice calculations aren't thrown off.
const sourceFileWithSnapshots = snapshots.reduceRight(
(sourceSoFar, nextSnapshot) => {
const {node} = nextSnapshot;
if (
!node ||
typeof node.start !== 'number' ||
typeof node.end !== 'number'
) {
throw new Error('Jest: no snapshot insert location found');
}
// A hack to prevent unexpected line breaks in the generated code
node.loc.end.line = node.loc.start.line;
return (
sourceSoFar.slice(0, node.start) +
generate(node, {
retainLines: true
}).code.trim() +
sourceSoFar.slice(node.end)
);
},
sourceFile
);
const newSourceFile = prettier
? runPrettier(
prettier,
sourceFilePath,
sourceFileWithSnapshots,
snapshotMatcherNames
)
: sourceFileWithSnapshots;
if (newSourceFile !== sourceFile) {
jestWriteFile(sourceFilePath, newSourceFile);
}
};
const groupSnapshotsBy = createKey => snapshots =>
snapshots.reduce((object, inlineSnapshot) => {
const key = createKey(inlineSnapshot);
return {
...object,
[key]: (object[key] || []).concat(inlineSnapshot)
};
}, {});
const groupSnapshotsByFrame = groupSnapshotsBy(({frame: {line, column}}) =>
typeof line === 'number' && typeof column === 'number'
? `${line}:${column - 1}`
: ''
);
const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file);
const indent = (snapshot, numIndents, indentation) => {
const lines = snapshot.split('\n');
// Prevent re-indentation of inline snapshots.
if (
lines.length >= 2 &&
lines[1].startsWith(indentation.repeat(numIndents + 1))
) {
return snapshot;
}
return lines
.map((line, index) => {
if (index === 0) {
// First line is either a 1-line snapshot or a blank line.
return line;
} else if (index !== lines.length - 1) {
// Do not indent empty lines.
if (line === '') {
return line;
}
// Not last line, indent one level deeper than expect call.
return indentation.repeat(numIndents + 1) + line;
} else {
// The last line should be placed on the same level as the expect call.
return indentation.repeat(numIndents) + line;
}
})
.join('\n');
};
const traverseAst = (snapshots, ast, snapshotMatcherNames) => {
const groupedSnapshots = groupSnapshotsByFrame(snapshots);
const remainingSnapshots = new Set(snapshots.map(({snapshot}) => snapshot));
traverseFast(ast, node => {
if (node.type !== 'CallExpression') return;
const {arguments: args, callee} = node;
if (
callee.type !== 'MemberExpression' ||
callee.property.type !== 'Identifier' ||
callee.property.loc == null
) {
return;
}
const {line, column} = callee.property.loc.start;
const snapshotsForFrame = groupedSnapshots[`${line}:${column}`];
if (!snapshotsForFrame) {
return;
}
if (snapshotsForFrame.length > 1) {
throw new Error(
'Jest: Multiple inline snapshots for the same call are not supported.'
);
}
const inlineSnapshot = snapshotsForFrame[0];
inlineSnapshot.node = node;
snapshotMatcherNames.push(callee.property.name);
const snapshotIndex = args.findIndex(
({type}) => type === 'TemplateLiteral' || type === 'StringLiteral'
);
const {snapshot} = inlineSnapshot;
remainingSnapshots.delete(snapshot);
const replacementNode = templateLiteral(
[
templateElement({
raw: (0, _utils.escapeBacktickString)(snapshot)
})
],
[]
);
if (snapshotIndex > -1) {
args[snapshotIndex] = replacementNode;
} else {
args.push(replacementNode);
}
});
if (remainingSnapshots.size) {
throw new Error("Jest: Couldn't locate all inline snapshots.");
}
};
const runPrettier = (
prettier,
sourceFilePath,
sourceFileWithSnapshots,
snapshotMatcherNames
) => {
// Resolve project configuration.
// For older versions of Prettier, do not load configuration.
const config = prettier.resolveConfig
? prettier.resolveConfig.sync(sourceFilePath, {
editorconfig: true
})
: null;
// Prioritize parser found in the project config.
// If not found detect the parser for the test file.
// For older versions of Prettier, fallback to a simple parser detection.
// @ts-expect-error - `inferredParser` is `string`
const inferredParser =
(config && typeof config.parser === 'string' && config.parser) ||
(prettier.getFileInfo
? prettier.getFileInfo.sync(sourceFilePath).inferredParser
: simpleDetectParser(sourceFilePath));
if (!inferredParser) {
throw new Error(
`Could not infer Prettier parser for file ${sourceFilePath}`
);
}
// Snapshots have now been inserted. Run prettier to make sure that the code is
// formatted, except snapshot indentation. Snapshots cannot be formatted until
// after the initial format because we don't know where the call expression
// will be placed (specifically its indentation), so we have to do two
// prettier.format calls back-to-back.
return prettier.format(
prettier.format(sourceFileWithSnapshots, {
...config,
filepath: sourceFilePath
}),
{
...config,
filepath: sourceFilePath,
parser: createFormattingParser(snapshotMatcherNames, inferredParser)
}
);
};
// This parser formats snapshots to the correct indentation.
const createFormattingParser =
(snapshotMatcherNames, inferredParser) => (text, parsers, options) => {
// Workaround for https://github.com/prettier/prettier/issues/3150
options.parser = inferredParser;
const ast = parsers[inferredParser](text, options);
traverse(ast, (node, ancestors) => {
if (node.type !== 'CallExpression') return;
const {arguments: args, callee} = node;
if (
callee.type !== 'MemberExpression' ||
callee.property.type !== 'Identifier' ||
!snapshotMatcherNames.includes(callee.property.name) ||
!callee.loc ||
callee.computed
) {
return;
}
let snapshotIndex;
let snapshot;
for (let i = 0; i < args.length; i++) {
const node = args[i];
if (node.type === 'TemplateLiteral') {
snapshotIndex = i;
snapshot = node.quasis[0].value.raw;
}
}
if (snapshot === undefined) {
return;
}
const parent = ancestors[ancestors.length - 1].node;
const startColumn =
isAwaitExpression(parent) && parent.loc
? parent.loc.start.column
: callee.loc.start.column;
const useSpaces = !options.useTabs;
snapshot = indent(
snapshot,
Math.ceil(
useSpaces
? startColumn / (options.tabWidth ?? 1)
: // Each tab is 2 characters.
startColumn / 2
),
useSpaces ? ' '.repeat(options.tabWidth ?? 1) : '\t'
);
const replacementNode = templateLiteral(
[
templateElement({
raw: snapshot
})
],
[]
);
args[snapshotIndex] = replacementNode;
});
return ast;
};
const simpleDetectParser = filePath => {
const extname = path.extname(filePath);
if (/\.tsx?$/.test(extname)) {
return 'typescript';
}
return 'babel';
};

View File

@ -0,0 +1,153 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.isSnapshotPath =
exports.buildSnapshotResolver =
exports.EXTENSION =
exports.DOT_EXTENSION =
void 0;
var path = _interopRequireWildcard(require('path'));
var _chalk = _interopRequireDefault(require('chalk'));
var _transform = require('@jest/transform');
var _jestUtil = require('jest-util');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const EXTENSION = 'snap';
exports.EXTENSION = EXTENSION;
const DOT_EXTENSION = `.${EXTENSION}`;
exports.DOT_EXTENSION = DOT_EXTENSION;
const isSnapshotPath = path => path.endsWith(DOT_EXTENSION);
exports.isSnapshotPath = isSnapshotPath;
const cache = new Map();
const buildSnapshotResolver = async (
config,
localRequire = (0, _transform.createTranspilingRequire)(config)
) => {
const key = config.rootDir;
const resolver =
cache.get(key) ??
(await createSnapshotResolver(await localRequire, config.snapshotResolver));
cache.set(key, resolver);
return resolver;
};
exports.buildSnapshotResolver = buildSnapshotResolver;
async function createSnapshotResolver(localRequire, snapshotResolverPath) {
return typeof snapshotResolverPath === 'string'
? createCustomSnapshotResolver(snapshotResolverPath, localRequire)
: createDefaultSnapshotResolver();
}
function createDefaultSnapshotResolver() {
return {
resolveSnapshotPath: testPath =>
path.join(
path.join(path.dirname(testPath), '__snapshots__'),
path.basename(testPath) + DOT_EXTENSION
),
resolveTestPath: snapshotPath =>
path.resolve(
path.dirname(snapshotPath),
'..',
path.basename(snapshotPath, DOT_EXTENSION)
),
testPathForConsistencyCheck: path.posix.join(
'consistency_check',
'__tests__',
'example.test.js'
)
};
}
async function createCustomSnapshotResolver(
snapshotResolverPath,
localRequire
) {
const custom = (0, _jestUtil.interopRequireDefault)(
await localRequire(snapshotResolverPath)
).default;
const keys = [
['resolveSnapshotPath', 'function'],
['resolveTestPath', 'function'],
['testPathForConsistencyCheck', 'string']
];
keys.forEach(([propName, requiredType]) => {
if (typeof custom[propName] !== requiredType) {
throw new TypeError(mustImplement(propName, requiredType));
}
});
const customResolver = {
resolveSnapshotPath: testPath =>
custom.resolveSnapshotPath(testPath, DOT_EXTENSION),
resolveTestPath: snapshotPath =>
custom.resolveTestPath(snapshotPath, DOT_EXTENSION),
testPathForConsistencyCheck: custom.testPathForConsistencyCheck
};
verifyConsistentTransformations(customResolver);
return customResolver;
}
function mustImplement(propName, requiredType) {
return `${_chalk.default.bold(
`Custom snapshot resolver must implement a \`${propName}\` as a ${requiredType}.`
)}\nDocumentation: https://jestjs.io/docs/configuration#snapshotresolver-string`;
}
function verifyConsistentTransformations(custom) {
const resolvedSnapshotPath = custom.resolveSnapshotPath(
custom.testPathForConsistencyCheck
);
const resolvedTestPath = custom.resolveTestPath(resolvedSnapshotPath);
if (resolvedTestPath !== custom.testPathForConsistencyCheck) {
throw new Error(
_chalk.default.bold(
`Custom snapshot resolver functions must transform paths consistently, i.e. expects resolveTestPath(resolveSnapshotPath('${custom.testPathForConsistencyCheck}')) === ${resolvedTestPath}`
)
);
}
}

View File

@ -0,0 +1,288 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var fs = _interopRequireWildcard(require('graceful-fs'));
var _jestMessageUtil = require('jest-message-util');
var _InlineSnapshots = require('./InlineSnapshots');
var _utils = require('./utils');
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var jestExistsFile =
globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class SnapshotState {
_counters;
_dirty;
// @ts-expect-error - seemingly unused?
_index;
_updateSnapshot;
_snapshotData;
_initialData;
_snapshotPath;
_inlineSnapshots;
_uncheckedKeys;
_prettierPath;
_rootDir;
snapshotFormat;
added;
expand;
matched;
unmatched;
updated;
constructor(snapshotPath, options) {
this._snapshotPath = snapshotPath;
const {data, dirty} = (0, _utils.getSnapshotData)(
this._snapshotPath,
options.updateSnapshot
);
this._initialData = data;
this._snapshotData = data;
this._dirty = dirty;
this._prettierPath = options.prettierPath ?? null;
this._inlineSnapshots = [];
this._uncheckedKeys = new Set(Object.keys(this._snapshotData));
this._counters = new Map();
this._index = 0;
this.expand = options.expand || false;
this.added = 0;
this.matched = 0;
this.unmatched = 0;
this._updateSnapshot = options.updateSnapshot;
this.updated = 0;
this.snapshotFormat = options.snapshotFormat;
this._rootDir = options.rootDir;
}
markSnapshotsAsCheckedForTest(testName) {
this._uncheckedKeys.forEach(uncheckedKey => {
if ((0, _utils.keyToTestName)(uncheckedKey) === testName) {
this._uncheckedKeys.delete(uncheckedKey);
}
});
}
_addSnapshot(key, receivedSerialized, options) {
this._dirty = true;
if (options.isInline) {
const error = options.error || new Error();
const lines = (0, _jestMessageUtil.getStackTraceLines)(
(0, _utils.removeLinesBeforeExternalMatcherTrap)(error.stack || '')
);
const frame = (0, _jestMessageUtil.getTopFrame)(lines);
if (!frame) {
throw new Error(
"Jest: Couldn't infer stack frame for inline snapshot."
);
}
this._inlineSnapshots.push({
frame,
snapshot: receivedSerialized
});
} else {
this._snapshotData[key] = receivedSerialized;
}
}
clear() {
this._snapshotData = this._initialData;
this._inlineSnapshots = [];
this._counters = new Map();
this._index = 0;
this.added = 0;
this.matched = 0;
this.unmatched = 0;
this.updated = 0;
}
save() {
const hasExternalSnapshots = Object.keys(this._snapshotData).length;
const hasInlineSnapshots = this._inlineSnapshots.length;
const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots;
const status = {
deleted: false,
saved: false
};
if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) {
if (hasExternalSnapshots) {
(0, _utils.saveSnapshotFile)(this._snapshotData, this._snapshotPath);
}
if (hasInlineSnapshots) {
(0, _InlineSnapshots.saveInlineSnapshots)(
this._inlineSnapshots,
this._rootDir,
this._prettierPath
);
}
status.saved = true;
} else if (!hasExternalSnapshots && jestExistsFile(this._snapshotPath)) {
if (this._updateSnapshot === 'all') {
fs.unlinkSync(this._snapshotPath);
}
status.deleted = true;
}
return status;
}
getUncheckedCount() {
return this._uncheckedKeys.size || 0;
}
getUncheckedKeys() {
return Array.from(this._uncheckedKeys);
}
removeUncheckedKeys() {
if (this._updateSnapshot === 'all' && this._uncheckedKeys.size) {
this._dirty = true;
this._uncheckedKeys.forEach(key => delete this._snapshotData[key]);
this._uncheckedKeys.clear();
}
}
match({testName, received, key, inlineSnapshot, isInline, error}) {
this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
const count = Number(this._counters.get(testName));
if (!key) {
key = (0, _utils.testNameToKey)(testName, count);
}
// Do not mark the snapshot as "checked" if the snapshot is inline and
// there's an external snapshot. This way the external snapshot can be
// removed with `--updateSnapshot`.
if (!(isInline && this._snapshotData[key] !== undefined)) {
this._uncheckedKeys.delete(key);
}
const receivedSerialized = (0, _utils.addExtraLineBreaks)(
(0, _utils.serialize)(received, undefined, this.snapshotFormat)
);
const expected = isInline ? inlineSnapshot : this._snapshotData[key];
const pass = expected === receivedSerialized;
const hasSnapshot = expected !== undefined;
const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath);
if (pass && !isInline) {
// Executing a snapshot file as JavaScript and writing the strings back
// when other snapshots have changed loses the proper escaping for some
// characters. Since we check every snapshot in every test, use the newly
// generated formatted string.
// Note that this is only relevant when a snapshot is added and the dirty
// flag is set.
this._snapshotData[key] = receivedSerialized;
}
// These are the conditions on when to write snapshots:
// * There's no snapshot file in a non-CI environment.
// * There is a snapshot file and we decided to update the snapshot.
// * There is a snapshot file, but it doesn't have this snaphsot.
// These are the conditions on when not to write snapshots:
// * The update flag is set to 'none'.
// * There's no snapshot file or a file without this snapshot on a CI environment.
if (
(hasSnapshot && this._updateSnapshot === 'all') ||
((!hasSnapshot || !snapshotIsPersisted) &&
(this._updateSnapshot === 'new' || this._updateSnapshot === 'all'))
) {
if (this._updateSnapshot === 'all') {
if (!pass) {
if (hasSnapshot) {
this.updated++;
} else {
this.added++;
}
this._addSnapshot(key, receivedSerialized, {
error,
isInline
});
} else {
this.matched++;
}
} else {
this._addSnapshot(key, receivedSerialized, {
error,
isInline
});
this.added++;
}
return {
actual: '',
count,
expected: '',
key,
pass: true
};
} else {
if (!pass) {
this.unmatched++;
return {
actual: (0, _utils.removeExtraLineBreaks)(receivedSerialized),
count,
expected:
expected !== undefined
? (0, _utils.removeExtraLineBreaks)(expected)
: undefined,
key,
pass: false
};
} else {
this.matched++;
return {
actual: '',
count,
expected: '',
key,
pass: true
};
}
}
}
fail(testName, _received, key) {
this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
const count = Number(this._counters.get(testName));
if (!key) {
key = (0, _utils.testNameToKey)(testName, count);
}
this._uncheckedKeys.delete(key);
this.unmatched++;
return key;
}
}
exports.default = SnapshotState;

View File

@ -0,0 +1,39 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.bForeground3 =
exports.bForeground2 =
exports.bBackground3 =
exports.bBackground2 =
exports.aForeground3 =
exports.aForeground2 =
exports.aBackground3 =
exports.aBackground2 =
void 0;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// https://jonasjacek.github.io/colors/
const aForeground2 = 90;
exports.aForeground2 = aForeground2;
const aBackground2 = 225;
exports.aBackground2 = aBackground2;
const bForeground2 = 23;
exports.bForeground2 = bForeground2;
const bBackground2 = 195;
exports.bBackground2 = bBackground2;
const aForeground3 = [0x80, 0, 0x80];
exports.aForeground3 = aForeground3;
const aBackground3 = [0xff, 0xd7, 0xff];
exports.aBackground3 = aBackground3;
const bForeground3 = [0, 0x5f, 0x5f];
exports.bForeground3 = bForeground3;
const bBackground3 = [0xd7, 0xff, 0xff];
exports.bBackground3 = bBackground3;

View File

@ -0,0 +1,132 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.dedentLines = void 0;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const getIndentationLength = line => {
const result = /^( {2})+/.exec(line);
return result === null ? 0 : result[0].length;
};
const dedentLine = line => line.slice(getIndentationLength(line));
// Return true if:
// "key": "value has multiple lines\n…
// "key has multiple lines\n…
const hasUnmatchedDoubleQuoteMarks = string => {
let n = 0;
let i = string.indexOf('"', 0);
while (i !== -1) {
if (i === 0 || string[i - 1] !== '\\') {
n += 1;
}
i = string.indexOf('"', i + 1);
}
return n % 2 !== 0;
};
const isFirstLineOfTag = line => /^( {2})*</.test(line);
// The length of the output array is the index of the next input line.
// Push dedented lines of start tag onto output and return true;
// otherwise return false because:
// * props include a multiline string (or text node, if props have markup)
// * start tag does not close
const dedentStartTag = (input, output) => {
let line = input[output.length];
output.push(dedentLine(line));
if (line.includes('>')) {
return true;
}
while (output.length < input.length) {
line = input[output.length];
if (hasUnmatchedDoubleQuoteMarks(line)) {
return false; // because props include a multiline string
} else if (isFirstLineOfTag(line)) {
// Recursion only if props have markup.
if (!dedentMarkup(input, output)) {
return false;
}
} else {
output.push(dedentLine(line));
if (line.includes('>')) {
return true;
}
}
}
return false;
};
// Push dedented lines of markup onto output and return true;
// otherwise return false because:
// * props include a multiline string
// * text has more than one adjacent line
// * markup does not close
const dedentMarkup = (input, output) => {
let line = input[output.length];
if (!dedentStartTag(input, output)) {
return false;
}
if (input[output.length - 1].includes('/>')) {
return true;
}
let isText = false;
const stack = [];
stack.push(getIndentationLength(line));
while (stack.length > 0 && output.length < input.length) {
line = input[output.length];
if (isFirstLineOfTag(line)) {
if (line.includes('</')) {
output.push(dedentLine(line));
stack.pop();
} else {
if (!dedentStartTag(input, output)) {
return false;
}
if (!input[output.length - 1].includes('/>')) {
stack.push(getIndentationLength(line));
}
}
isText = false;
} else {
if (isText) {
return false; // because text has more than one adjacent line
}
const indentationLengthOfTag = stack[stack.length - 1];
output.push(line.slice(indentationLengthOfTag + 2));
isText = true;
}
}
return stack.length === 0;
};
// Return lines unindented by heuristic;
// otherwise return null because:
// * props include a multiline string
// * text has more than one adjacent line
// * markup does not close
const dedentLines = input => {
const output = [];
while (output.length < input.length) {
const line = input[output.length];
if (hasUnmatchedDoubleQuoteMarks(line)) {
return null;
} else if (isFirstLineOfTag(line)) {
if (!dedentMarkup(input, output)) {
return null;
}
} else {
output.push(dedentLine(line));
}
}
return output;
};
exports.dedentLines = dedentLines;

View File

@ -0,0 +1,186 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type {Config} from '@jest/types';
import type {MatcherContext} from 'expect';
import type {MatcherFunctionWithContext} from 'expect';
import {Plugin as Plugin_2} from 'pretty-format';
import {Plugins} from 'pretty-format';
import type {PrettyFormatOptions} from 'pretty-format';
export declare const addSerializer: (plugin: Plugin_2) => void;
export declare const buildSnapshotResolver: (
config: Config.ProjectConfig,
localRequire?: Promise<LocalRequire> | LocalRequire,
) => Promise<SnapshotResolver>;
export declare const cleanup: (
fileSystem: FileSystem_2,
update: Config.SnapshotUpdateState,
snapshotResolver: SnapshotResolver,
testPathIgnorePatterns?: Config.ProjectConfig['testPathIgnorePatterns'],
) => {
filesRemoved: number;
filesRemovedList: Array<string>;
};
export declare interface Context extends MatcherContext {
snapshotState: SnapshotState;
}
export declare const EXTENSION = 'snap';
declare interface FileSystem_2 {
exists(path: string): boolean;
matchFiles(pattern: RegExp | string): Array<string>;
}
export declare const getSerializers: () => Plugins;
export declare const isSnapshotPath: (path: string) => boolean;
declare type LocalRequire = (module: string) => unknown;
declare type SaveStatus = {
deleted: boolean;
saved: boolean;
};
declare type SnapshotFormat = Omit<PrettyFormatOptions, 'compareKeys'>;
export declare interface SnapshotMatchers<R extends void | Promise<void>, T> {
/**
* This ensures that a value matches the most recent snapshot with property matchers.
* Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information.
*/
toMatchSnapshot(hint?: string): R;
/**
* This ensures that a value matches the most recent snapshot.
* Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information.
*/
toMatchSnapshot<U extends Record<keyof T, unknown>>(
propertyMatchers: Partial<U>,
hint?: string,
): R;
/**
* This ensures that a value matches the most recent snapshot with property matchers.
* Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
* Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information.
*/
toMatchInlineSnapshot(snapshot?: string): R;
/**
* This ensures that a value matches the most recent snapshot with property matchers.
* Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
* Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information.
*/
toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(
propertyMatchers: Partial<U>,
snapshot?: string,
): R;
/**
* Used to test that a function throws a error matching the most recent snapshot when it is called.
*/
toThrowErrorMatchingSnapshot(hint?: string): R;
/**
* Used to test that a function throws a error matching the most recent snapshot when it is called.
* Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
*/
toThrowErrorMatchingInlineSnapshot(snapshot?: string): R;
}
declare type SnapshotMatchOptions = {
readonly testName: string;
readonly received: unknown;
readonly key?: string;
readonly inlineSnapshot?: string;
readonly isInline: boolean;
readonly error?: Error;
};
export declare type SnapshotResolver = {
/** Resolves from `testPath` to snapshot path. */
resolveSnapshotPath(testPath: string, snapshotExtension?: string): string;
/** Resolves from `snapshotPath` to test path. */
resolveTestPath(snapshotPath: string, snapshotExtension?: string): string;
/** Example test path, used for preflight consistency check of the implementation above. */
testPathForConsistencyCheck: string;
};
declare type SnapshotReturnOptions = {
readonly actual: string;
readonly count: number;
readonly expected?: string;
readonly key: string;
readonly pass: boolean;
};
export declare class SnapshotState {
private _counters;
private _dirty;
private _index;
private readonly _updateSnapshot;
private _snapshotData;
private readonly _initialData;
private readonly _snapshotPath;
private _inlineSnapshots;
private readonly _uncheckedKeys;
private readonly _prettierPath;
private readonly _rootDir;
readonly snapshotFormat: SnapshotFormat;
added: number;
expand: boolean;
matched: number;
unmatched: number;
updated: number;
constructor(snapshotPath: string, options: SnapshotStateOptions);
markSnapshotsAsCheckedForTest(testName: string): void;
private _addSnapshot;
clear(): void;
save(): SaveStatus;
getUncheckedCount(): number;
getUncheckedKeys(): Array<string>;
removeUncheckedKeys(): void;
match({
testName,
received,
key,
inlineSnapshot,
isInline,
error,
}: SnapshotMatchOptions): SnapshotReturnOptions;
fail(testName: string, _received: unknown, key?: string): string;
}
declare type SnapshotStateOptions = {
readonly updateSnapshot: Config.SnapshotUpdateState;
readonly prettierPath?: string | null;
readonly expand?: boolean;
readonly snapshotFormat: SnapshotFormat;
readonly rootDir: string;
};
export declare const toMatchInlineSnapshot: MatcherFunctionWithContext<
Context,
[propertiesOrSnapshot?: object | string, inlineSnapshot?: string]
>;
export declare const toMatchSnapshot: MatcherFunctionWithContext<
Context,
[propertiesOrHint?: object | string, hint?: string]
>;
export declare const toThrowErrorMatchingInlineSnapshot: MatcherFunctionWithContext<
Context,
[inlineSnapshot?: string, fromPromise?: boolean]
>;
export declare const toThrowErrorMatchingSnapshot: MatcherFunctionWithContext<
Context,
[hint?: string, fromPromise?: boolean]
>;
export {};

View File

@ -0,0 +1,591 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
Object.defineProperty(exports, 'EXTENSION', {
enumerable: true,
get: function () {
return _SnapshotResolver.EXTENSION;
}
});
Object.defineProperty(exports, 'SnapshotState', {
enumerable: true,
get: function () {
return _State.default;
}
});
Object.defineProperty(exports, 'addSerializer', {
enumerable: true,
get: function () {
return _plugins.addSerializer;
}
});
Object.defineProperty(exports, 'buildSnapshotResolver', {
enumerable: true,
get: function () {
return _SnapshotResolver.buildSnapshotResolver;
}
});
exports.cleanup = void 0;
Object.defineProperty(exports, 'getSerializers', {
enumerable: true,
get: function () {
return _plugins.getSerializers;
}
});
Object.defineProperty(exports, 'isSnapshotPath', {
enumerable: true,
get: function () {
return _SnapshotResolver.isSnapshotPath;
}
});
exports.toThrowErrorMatchingSnapshot =
exports.toThrowErrorMatchingInlineSnapshot =
exports.toMatchSnapshot =
exports.toMatchInlineSnapshot =
void 0;
var fs = _interopRequireWildcard(require('graceful-fs'));
var _jestMatcherUtils = require('jest-matcher-utils');
var _SnapshotResolver = require('./SnapshotResolver');
var _printSnapshot = require('./printSnapshot');
var _utils = require('./utils');
var _plugins = require('./plugins');
var _State = _interopRequireDefault(require('./State'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var jestExistsFile =
globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const DID_NOT_THROW = 'Received function did not throw'; // same as toThrow
const NOT_SNAPSHOT_MATCHERS = `Snapshot matchers cannot be used with ${(0,
_jestMatcherUtils.BOLD_WEIGHT)('not')}`;
const INDENTATION_REGEX = /^([^\S\n]*)\S/m;
// Display name in report when matcher fails same as in snapshot file,
// but with optional hint argument in bold weight.
const printSnapshotName = (concatenatedBlockNames = '', hint = '', count) => {
const hasNames = concatenatedBlockNames.length !== 0;
const hasHint = hint.length !== 0;
return `Snapshot name: \`${
hasNames ? (0, _utils.escapeBacktickString)(concatenatedBlockNames) : ''
}${hasNames && hasHint ? ': ' : ''}${
hasHint
? (0, _jestMatcherUtils.BOLD_WEIGHT)(
(0, _utils.escapeBacktickString)(hint)
)
: ''
} ${count}\``;
};
function stripAddedIndentation(inlineSnapshot) {
// Find indentation if exists.
const match = inlineSnapshot.match(INDENTATION_REGEX);
if (!match || !match[1]) {
// No indentation.
return inlineSnapshot;
}
const indentation = match[1];
const lines = inlineSnapshot.split('\n');
if (lines.length <= 2) {
// Must be at least 3 lines.
return inlineSnapshot;
}
if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') {
// If not blank first and last lines, abort.
return inlineSnapshot;
}
for (let i = 1; i < lines.length - 1; i++) {
if (lines[i] !== '') {
if (lines[i].indexOf(indentation) !== 0) {
// All lines except first and last should either be blank or have the same
// indent as the first line (or more). If this isn't the case we don't
// want to touch the snapshot at all.
return inlineSnapshot;
}
lines[i] = lines[i].substring(indentation.length);
}
}
// Last line is a special case because it won't have the same indent as others
// but may still have been given some indent to line up.
lines[lines.length - 1] = '';
// Return inline snapshot, now at indent 0.
inlineSnapshot = lines.join('\n');
return inlineSnapshot;
}
const fileExists = (filePath, fileSystem) =>
fileSystem.exists(filePath) || jestExistsFile(filePath);
const cleanup = (
fileSystem,
update,
snapshotResolver,
testPathIgnorePatterns
) => {
const pattern = `\\.${_SnapshotResolver.EXTENSION}$`;
const files = fileSystem.matchFiles(pattern);
let testIgnorePatternsRegex = null;
if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) {
testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|'));
}
const list = files.filter(snapshotFile => {
const testPath = snapshotResolver.resolveTestPath(snapshotFile);
// ignore snapshots of ignored tests
if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) {
return false;
}
if (!fileExists(testPath, fileSystem)) {
if (update === 'all') {
fs.unlinkSync(snapshotFile);
}
return true;
}
return false;
});
return {
filesRemoved: list.length,
filesRemovedList: list
};
};
exports.cleanup = cleanup;
const toMatchSnapshot = function (received, propertiesOrHint, hint) {
const matcherName = 'toMatchSnapshot';
let properties;
const length = arguments.length;
if (length === 2 && typeof propertiesOrHint === 'string') {
hint = propertiesOrHint;
} else if (length >= 2) {
if (typeof propertiesOrHint !== 'object' || propertiesOrHint === null) {
const options = {
isNot: this.isNot,
promise: this.promise
};
let printedWithType = (0, _jestMatcherUtils.printWithType)(
'Expected properties',
propertiesOrHint,
_printSnapshot.printExpected
);
if (length === 3) {
options.secondArgument = 'hint';
options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT;
if (propertiesOrHint == null) {
printedWithType +=
"\n\nTo provide a hint without properties: toMatchSnapshot('hint')";
}
}
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
_printSnapshot.PROPERTIES_ARG,
options
),
`Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)(
'properties'
)} must be an object`,
printedWithType
)
);
}
// Future breaking change: Snapshot hint must be a string
// if (arguments.length === 3 && typeof hint !== 'string') {}
properties = propertiesOrHint;
}
return _toMatchSnapshot({
context: this,
hint,
isInline: false,
matcherName,
properties,
received
});
};
exports.toMatchSnapshot = toMatchSnapshot;
const toMatchInlineSnapshot = function (
received,
propertiesOrSnapshot,
inlineSnapshot
) {
const matcherName = 'toMatchInlineSnapshot';
let properties;
const length = arguments.length;
if (length === 2 && typeof propertiesOrSnapshot === 'string') {
inlineSnapshot = propertiesOrSnapshot;
} else if (length >= 2) {
const options = {
isNot: this.isNot,
promise: this.promise
};
if (length === 3) {
options.secondArgument = _printSnapshot.SNAPSHOT_ARG;
options.secondArgumentColor = _printSnapshot.noColor;
}
if (
typeof propertiesOrSnapshot !== 'object' ||
propertiesOrSnapshot === null
) {
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
_printSnapshot.PROPERTIES_ARG,
options
),
`Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)(
'properties'
)} must be an object`,
(0, _jestMatcherUtils.printWithType)(
'Expected properties',
propertiesOrSnapshot,
_printSnapshot.printExpected
)
)
);
}
if (length === 3 && typeof inlineSnapshot !== 'string') {
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
_printSnapshot.PROPERTIES_ARG,
options
),
'Inline snapshot must be a string',
(0, _jestMatcherUtils.printWithType)(
'Inline snapshot',
inlineSnapshot,
_utils.serialize
)
)
);
}
properties = propertiesOrSnapshot;
}
return _toMatchSnapshot({
context: this,
inlineSnapshot:
inlineSnapshot !== undefined
? stripAddedIndentation(inlineSnapshot)
: undefined,
isInline: true,
matcherName,
properties,
received
});
};
exports.toMatchInlineSnapshot = toMatchInlineSnapshot;
const _toMatchSnapshot = config => {
const {context, hint, inlineSnapshot, isInline, matcherName, properties} =
config;
let {received} = config;
context.dontThrow && context.dontThrow();
const {currentConcurrentTestName, isNot, snapshotState} = context;
const currentTestName =
currentConcurrentTestName?.() ?? context.currentTestName;
if (isNot) {
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _printSnapshot.matcherHintFromConfig)(config, false),
NOT_SNAPSHOT_MATCHERS
)
);
}
if (snapshotState == null) {
// Because the state is the problem, this is not a matcher error.
// Call generic stringify from jest-matcher-utils package
// because uninitialized snapshot state does not need snapshot serializers.
throw new Error(
`${(0, _printSnapshot.matcherHintFromConfig)(config, false)}\n\n` +
'Snapshot state must be initialized' +
`\n\n${(0, _jestMatcherUtils.printWithType)(
'Snapshot state',
snapshotState,
_jestMatcherUtils.stringify
)}`
);
}
const fullTestName =
currentTestName && hint
? `${currentTestName}: ${hint}`
: currentTestName || ''; // future BREAKING change: || hint
if (typeof properties === 'object') {
if (typeof received !== 'object' || received === null) {
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _printSnapshot.matcherHintFromConfig)(config, false),
`${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'received'
)} value must be an object when the matcher has ${(0,
_jestMatcherUtils.EXPECTED_COLOR)('properties')}`,
(0, _jestMatcherUtils.printWithType)(
'Received',
received,
_printSnapshot.printReceived
)
)
);
}
const propertyPass = context.equals(received, properties, [
context.utils.iterableEquality,
context.utils.subsetEquality
]);
if (!propertyPass) {
const key = snapshotState.fail(fullTestName, received);
const matched = /(\d+)$/.exec(key);
const count = matched === null ? 1 : Number(matched[1]);
const message = () =>
`${(0, _printSnapshot.matcherHintFromConfig)(
config,
false
)}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n${(0,
_printSnapshot.printPropertiesAndReceived)(
properties,
received,
snapshotState.expand
)}`;
return {
message,
name: matcherName,
pass: false
};
} else {
received = (0, _utils.deepMerge)(received, properties);
}
}
const result = snapshotState.match({
error: context.error,
inlineSnapshot,
isInline,
received,
testName: fullTestName
});
const {actual, count, expected, pass} = result;
if (pass) {
return {
message: () => '',
pass: true
};
}
const message =
expected === undefined
? () =>
`${(0, _printSnapshot.matcherHintFromConfig)(
config,
true
)}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n` +
`New snapshot was ${(0, _jestMatcherUtils.BOLD_WEIGHT)(
'not written'
)}. The update flag ` +
'must be explicitly passed to write a new snapshot.\n\n' +
'This is likely because this test is run in a continuous integration ' +
'(CI) environment in which snapshots are not written by default.\n\n' +
`Received:${actual.includes('\n') ? '\n' : ' '}${(0,
_printSnapshot.bReceivedColor)(actual)}`
: () =>
`${(0, _printSnapshot.matcherHintFromConfig)(
config,
true
)}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n${(0,
_printSnapshot.printSnapshotAndReceived)(
expected,
actual,
received,
snapshotState.expand,
snapshotState.snapshotFormat
)}`;
// Passing the actual and expected objects so that a custom reporter
// could access them, for example in order to display a custom visual diff,
// or create a different error message
return {
actual,
expected,
message,
name: matcherName,
pass: false
};
};
const toThrowErrorMatchingSnapshot = function (received, hint, fromPromise) {
const matcherName = 'toThrowErrorMatchingSnapshot';
// Future breaking change: Snapshot hint must be a string
// if (hint !== undefined && typeof hint !== string) {}
return _toThrowErrorMatchingSnapshot(
{
context: this,
hint,
isInline: false,
matcherName,
received
},
fromPromise
);
};
exports.toThrowErrorMatchingSnapshot = toThrowErrorMatchingSnapshot;
const toThrowErrorMatchingInlineSnapshot = function (
received,
inlineSnapshot,
fromPromise
) {
const matcherName = 'toThrowErrorMatchingInlineSnapshot';
if (inlineSnapshot !== undefined && typeof inlineSnapshot !== 'string') {
const options = {
expectedColor: _printSnapshot.noColor,
isNot: this.isNot,
promise: this.promise
};
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
_printSnapshot.SNAPSHOT_ARG,
options
),
'Inline snapshot must be a string',
(0, _jestMatcherUtils.printWithType)(
'Inline snapshot',
inlineSnapshot,
_utils.serialize
)
)
);
}
return _toThrowErrorMatchingSnapshot(
{
context: this,
inlineSnapshot:
inlineSnapshot !== undefined
? stripAddedIndentation(inlineSnapshot)
: undefined,
isInline: true,
matcherName,
received
},
fromPromise
);
};
exports.toThrowErrorMatchingInlineSnapshot = toThrowErrorMatchingInlineSnapshot;
const _toThrowErrorMatchingSnapshot = (config, fromPromise) => {
const {context, hint, inlineSnapshot, isInline, matcherName, received} =
config;
context.dontThrow && context.dontThrow();
const {isNot, promise} = context;
if (!fromPromise) {
if (typeof received !== 'function') {
const options = {
isNot,
promise
};
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
'',
options
),
`${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'received'
)} value must be a function`,
(0, _jestMatcherUtils.printWithType)(
'Received',
received,
_printSnapshot.printReceived
)
)
);
}
}
if (isNot) {
throw new Error(
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _printSnapshot.matcherHintFromConfig)(config, false),
NOT_SNAPSHOT_MATCHERS
)
);
}
let error;
if (fromPromise) {
error = received;
} else {
try {
received();
} catch (e) {
error = e;
}
}
if (error === undefined) {
// Because the received value is a function, this is not a matcher error.
throw new Error(
`${(0, _printSnapshot.matcherHintFromConfig)(
config,
false
)}\n\n${DID_NOT_THROW}`
);
}
return _toMatchSnapshot({
context,
hint,
inlineSnapshot,
isInline,
matcherName,
received: error.message
});
};

View File

@ -0,0 +1,47 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.test = exports.serialize = exports.default = void 0;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const serialize = (val, config, indentation, depth, refs, printer) => {
// Serialize a non-default name, even if config.printFunctionName is false.
const name = val.getMockName();
const nameString = name === 'jest.fn()' ? '' : ` ${name}`;
let callsString = '';
if (val.mock.calls.length !== 0) {
const indentationNext = indentation + config.indent;
callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer(
val.mock.calls,
config,
indentationNext,
depth,
refs
)}${config.min ? ', ' : ','}${
config.spacingOuter
}${indentationNext}"results": ${printer(
val.mock.results,
config,
indentationNext,
depth,
refs
)}${config.min ? '' : ','}${config.spacingOuter}${indentation}}`;
}
return `[MockFunction${nameString}]${callsString}`;
};
exports.serialize = serialize;
const test = val => val && !!val._isMockFunction;
exports.test = test;
const plugin = {
serialize,
test
};
var _default = plugin;
exports.default = _default;

View File

@ -0,0 +1,43 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.getSerializers = exports.addSerializer = void 0;
var _prettyFormat = require('pretty-format');
var _mockSerializer = _interopRequireDefault(require('./mockSerializer'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {
DOMCollection,
DOMElement,
Immutable,
ReactElement,
ReactTestComponent,
AsymmetricMatcher
} = _prettyFormat.plugins;
let PLUGINS = [
ReactTestComponent,
ReactElement,
DOMElement,
DOMCollection,
Immutable,
_mockSerializer.default,
AsymmetricMatcher
];
// Prepend to list so the last added is the first tested.
const addSerializer = plugin => {
PLUGINS = [plugin].concat(PLUGINS);
};
exports.addSerializer = addSerializer;
const getSerializers = () => PLUGINS;
exports.getSerializers = getSerializers;

View File

@ -0,0 +1,340 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.printSnapshotAndReceived =
exports.printReceived =
exports.printPropertiesAndReceived =
exports.printExpected =
exports.noColor =
exports.matcherHintFromConfig =
exports.getSnapshotColorForChalkInstance =
exports.getReceivedColorForChalkInstance =
exports.bReceivedColor =
exports.aSnapshotColor =
exports.SNAPSHOT_ARG =
exports.PROPERTIES_ARG =
exports.HINT_ARG =
void 0;
var _chalk = _interopRequireDefault(require('chalk'));
var _expectUtils = require('@jest/expect-utils');
var _jestDiff = require('jest-diff');
var _jestGetType = require('jest-get-type');
var _jestMatcherUtils = require('jest-matcher-utils');
var _prettyFormat = require('pretty-format');
var _colors = require('./colors');
var _dedentLines = require('./dedentLines');
var _utils = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const getSnapshotColorForChalkInstance = chalkInstance => {
const level = chalkInstance.level;
if (level === 3) {
return chalkInstance
.rgb(
_colors.aForeground3[0],
_colors.aForeground3[1],
_colors.aForeground3[2]
)
.bgRgb(
_colors.aBackground3[0],
_colors.aBackground3[1],
_colors.aBackground3[2]
);
}
if (level === 2) {
return chalkInstance
.ansi256(_colors.aForeground2)
.bgAnsi256(_colors.aBackground2);
}
return chalkInstance.magenta.bgYellowBright;
};
exports.getSnapshotColorForChalkInstance = getSnapshotColorForChalkInstance;
const getReceivedColorForChalkInstance = chalkInstance => {
const level = chalkInstance.level;
if (level === 3) {
return chalkInstance
.rgb(
_colors.bForeground3[0],
_colors.bForeground3[1],
_colors.bForeground3[2]
)
.bgRgb(
_colors.bBackground3[0],
_colors.bBackground3[1],
_colors.bBackground3[2]
);
}
if (level === 2) {
return chalkInstance
.ansi256(_colors.bForeground2)
.bgAnsi256(_colors.bBackground2);
}
return chalkInstance.cyan.bgWhiteBright; // also known as teal
};
exports.getReceivedColorForChalkInstance = getReceivedColorForChalkInstance;
const aSnapshotColor = getSnapshotColorForChalkInstance(_chalk.default);
exports.aSnapshotColor = aSnapshotColor;
const bReceivedColor = getReceivedColorForChalkInstance(_chalk.default);
exports.bReceivedColor = bReceivedColor;
const noColor = string => string;
exports.noColor = noColor;
const HINT_ARG = 'hint';
exports.HINT_ARG = HINT_ARG;
const SNAPSHOT_ARG = 'snapshot';
exports.SNAPSHOT_ARG = SNAPSHOT_ARG;
const PROPERTIES_ARG = 'properties';
exports.PROPERTIES_ARG = PROPERTIES_ARG;
const matcherHintFromConfig = (
{context: {isNot, promise}, hint, inlineSnapshot, matcherName, properties},
isUpdatable
) => {
const options = {
isNot,
promise
};
if (isUpdatable) {
options.receivedColor = bReceivedColor;
}
let expectedArgument = '';
if (typeof properties === 'object') {
expectedArgument = PROPERTIES_ARG;
if (isUpdatable) {
options.expectedColor = noColor;
}
if (typeof hint === 'string' && hint.length !== 0) {
options.secondArgument = HINT_ARG;
options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT;
} else if (typeof inlineSnapshot === 'string') {
options.secondArgument = SNAPSHOT_ARG;
if (isUpdatable) {
options.secondArgumentColor = aSnapshotColor;
} else {
options.secondArgumentColor = noColor;
}
}
} else {
if (typeof hint === 'string' && hint.length !== 0) {
expectedArgument = HINT_ARG;
options.expectedColor = _jestMatcherUtils.BOLD_WEIGHT;
} else if (typeof inlineSnapshot === 'string') {
expectedArgument = SNAPSHOT_ARG;
if (isUpdatable) {
options.expectedColor = aSnapshotColor;
}
}
}
return (0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
expectedArgument,
options
);
};
// Given array of diffs, return string:
// * include common substrings
// * exclude change substrings which have opposite op
// * include change substrings which have argument op
// with change color only if there is a common substring
exports.matcherHintFromConfig = matcherHintFromConfig;
const joinDiffs = (diffs, op, hasCommon) =>
diffs.reduce(
(reduced, diff) =>
reduced +
(diff[0] === _jestDiff.DIFF_EQUAL
? diff[1]
: diff[0] !== op
? ''
: hasCommon
? (0, _jestMatcherUtils.INVERTED_COLOR)(diff[1])
: diff[1]),
''
);
const isLineDiffable = received => {
const receivedType = (0, _jestGetType.getType)(received);
if ((0, _jestGetType.isPrimitive)(received)) {
return typeof received === 'string';
}
if (
receivedType === 'date' ||
receivedType === 'function' ||
receivedType === 'regexp'
) {
return false;
}
if (received instanceof Error) {
return false;
}
if (
receivedType === 'object' &&
typeof received.asymmetricMatch === 'function'
) {
return false;
}
return true;
};
const printExpected = val =>
(0, _jestMatcherUtils.EXPECTED_COLOR)((0, _utils.minify)(val));
exports.printExpected = printExpected;
const printReceived = val =>
(0, _jestMatcherUtils.RECEIVED_COLOR)((0, _utils.minify)(val));
exports.printReceived = printReceived;
const printPropertiesAndReceived = (
properties,
received,
expand // CLI options: true if `--expand` or false if `--no-expand`
) => {
const aAnnotation = 'Expected properties';
const bAnnotation = 'Received value';
if (isLineDiffable(properties) && isLineDiffable(received)) {
const {replacedExpected, replacedReceived} = (0,
_jestMatcherUtils.replaceMatchedToAsymmetricMatcher)(
properties,
received,
[],
[]
);
return (0, _jestDiff.diffLinesUnified)(
(0, _utils.serialize)(replacedExpected).split('\n'),
(0, _utils.serialize)(
(0, _expectUtils.getObjectSubset)(replacedReceived, replacedExpected)
).split('\n'),
{
aAnnotation,
aColor: _jestMatcherUtils.EXPECTED_COLOR,
bAnnotation,
bColor: _jestMatcherUtils.RECEIVED_COLOR,
changeLineTrailingSpaceColor: _chalk.default.bgYellow,
commonLineTrailingSpaceColor: _chalk.default.bgYellow,
emptyFirstOrLastLinePlaceholder: '↵',
// U+21B5
expand,
includeChangeCounts: true
}
);
}
const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
aAnnotation,
bAnnotation
);
return `${printLabel(aAnnotation) + printExpected(properties)}\n${printLabel(
bAnnotation
)}${printReceived(received)}`;
};
exports.printPropertiesAndReceived = printPropertiesAndReceived;
const MAX_DIFF_STRING_LENGTH = 20000;
const printSnapshotAndReceived = (a, b, received, expand, snapshotFormat) => {
const aAnnotation = 'Snapshot';
const bAnnotation = 'Received';
const aColor = aSnapshotColor;
const bColor = bReceivedColor;
const options = {
aAnnotation,
aColor,
bAnnotation,
bColor,
changeLineTrailingSpaceColor: noColor,
commonLineTrailingSpaceColor: _chalk.default.bgYellow,
emptyFirstOrLastLinePlaceholder: '↵',
// U+21B5
expand,
includeChangeCounts: true
};
if (typeof received === 'string') {
if (
a.length >= 2 &&
a.startsWith('"') &&
a.endsWith('"') &&
b === (0, _prettyFormat.format)(received)
) {
// If snapshot looks like default serialization of a string
// and received is string which has default serialization.
if (!a.includes('\n') && !b.includes('\n')) {
// If neither string is multiline,
// display as labels and quoted strings.
let aQuoted = a;
let bQuoted = b;
if (
a.length - 2 <= MAX_DIFF_STRING_LENGTH &&
b.length - 2 <= MAX_DIFF_STRING_LENGTH
) {
const diffs = (0, _jestDiff.diffStringsRaw)(
a.slice(1, -1),
b.slice(1, -1),
true
);
const hasCommon = diffs.some(
diff => diff[0] === _jestDiff.DIFF_EQUAL
);
aQuoted = `"${joinDiffs(diffs, _jestDiff.DIFF_DELETE, hasCommon)}"`;
bQuoted = `"${joinDiffs(diffs, _jestDiff.DIFF_INSERT, hasCommon)}"`;
}
const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
aAnnotation,
bAnnotation
);
return `${printLabel(aAnnotation) + aColor(aQuoted)}\n${printLabel(
bAnnotation
)}${bColor(bQuoted)}`;
}
// Else either string is multiline, so display as unquoted strings.
a = (0, _utils.deserializeString)(a); // hypothetical expected string
b = received; // not serialized
}
// Else expected had custom serialization or was not a string
// or received has custom serialization.
return a.length <= MAX_DIFF_STRING_LENGTH &&
b.length <= MAX_DIFF_STRING_LENGTH
? (0, _jestDiff.diffStringsUnified)(a, b, options)
: (0, _jestDiff.diffLinesUnified)(a.split('\n'), b.split('\n'), options);
}
if (isLineDiffable(received)) {
const aLines2 = a.split('\n');
const bLines2 = b.split('\n');
// Fall through to fix a regression for custom serializers
// like jest-snapshot-serializer-raw that ignore the indent option.
const b0 = (0, _utils.serialize)(received, 0, snapshotFormat);
if (b0 !== b) {
const aLines0 = (0, _dedentLines.dedentLines)(aLines2);
if (aLines0 !== null) {
// Compare lines without indentation.
const bLines0 = b0.split('\n');
return (0, _jestDiff.diffLinesUnified2)(
aLines2,
bLines2,
aLines0,
bLines0,
options
);
}
}
// Fall back because:
// * props include a multiline string
// * text has more than one adjacent line
// * markup does not close
return (0, _jestDiff.diffLinesUnified)(aLines2, bLines2, options);
}
const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
aAnnotation,
bAnnotation
);
return `${printLabel(aAnnotation) + aColor(a)}\n${printLabel(
bAnnotation
)}${bColor(b)}`;
};
exports.printSnapshotAndReceived = printSnapshotAndReceived;

View File

@ -0,0 +1 @@
'use strict';

View File

@ -0,0 +1,320 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.testNameToKey =
exports.serialize =
exports.saveSnapshotFile =
exports.removeLinesBeforeExternalMatcherTrap =
exports.removeExtraLineBreaks =
exports.minify =
exports.keyToTestName =
exports.getSnapshotData =
exports.escapeBacktickString =
exports.ensureDirectoryExists =
exports.deserializeString =
exports.deepMerge =
exports.addExtraLineBreaks =
exports.SNAPSHOT_VERSION_WARNING =
exports.SNAPSHOT_VERSION =
exports.SNAPSHOT_GUIDE_LINK =
void 0;
var path = _interopRequireWildcard(require('path'));
var _chalk = _interopRequireDefault(require('chalk'));
var fs = _interopRequireWildcard(require('graceful-fs'));
var _naturalCompare = _interopRequireDefault(require('natural-compare'));
var _prettyFormat = require('pretty-format');
var _plugins = require('./plugins');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var jestWriteFile =
globalThis[Symbol.for('jest-native-write-file')] || fs.writeFileSync;
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var jestReadFile =
globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync;
var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
var jestExistsFile =
globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const SNAPSHOT_VERSION = '1';
exports.SNAPSHOT_VERSION = SNAPSHOT_VERSION;
const SNAPSHOT_VERSION_REGEXP = /^\/\/ Jest Snapshot v(.+),/;
const SNAPSHOT_GUIDE_LINK = 'https://goo.gl/fbAQLP';
exports.SNAPSHOT_GUIDE_LINK = SNAPSHOT_GUIDE_LINK;
const SNAPSHOT_VERSION_WARNING = _chalk.default.yellow(
`${_chalk.default.bold('Warning')}: Before you upgrade snapshots, ` +
'we recommend that you revert any local changes to tests or other code, ' +
'to ensure that you do not store invalid state.'
);
exports.SNAPSHOT_VERSION_WARNING = SNAPSHOT_VERSION_WARNING;
const writeSnapshotVersion = () =>
`// Jest Snapshot v${SNAPSHOT_VERSION}, ${SNAPSHOT_GUIDE_LINK}`;
const validateSnapshotVersion = snapshotContents => {
const versionTest = SNAPSHOT_VERSION_REGEXP.exec(snapshotContents);
const version = versionTest && versionTest[1];
if (!version) {
return new Error(
_chalk.default.red(
`${_chalk.default.bold(
'Outdated snapshot'
)}: No snapshot header found. ` +
'Jest 19 introduced versioned snapshots to ensure all developers ' +
'on a project are using the same version of Jest. ' +
'Please update all snapshots during this upgrade of Jest.\n\n'
) + SNAPSHOT_VERSION_WARNING
);
}
if (version < SNAPSHOT_VERSION) {
return new Error(
// eslint-disable-next-line prefer-template
_chalk.default.red(
`${_chalk.default.red.bold(
'Outdated snapshot'
)}: The version of the snapshot ` +
'file associated with this test is outdated. The snapshot file ' +
'version ensures that all developers on a project are using ' +
'the same version of Jest. ' +
'Please update all snapshots during this upgrade of Jest.'
) +
'\n\n' +
`Expected: v${SNAPSHOT_VERSION}\n` +
`Received: v${version}\n\n` +
SNAPSHOT_VERSION_WARNING
);
}
if (version > SNAPSHOT_VERSION) {
return new Error(
// eslint-disable-next-line prefer-template
_chalk.default.red(
`${_chalk.default.red.bold(
'Outdated Jest version'
)}: The version of this ` +
'snapshot file indicates that this project is meant to be used ' +
'with a newer version of Jest. The snapshot file version ensures ' +
'that all developers on a project are using the same version of ' +
'Jest. Please update your version of Jest and re-run the tests.'
) +
'\n\n' +
`Expected: v${SNAPSHOT_VERSION}\n` +
`Received: v${version}`
);
}
return null;
};
function isObject(item) {
return item != null && typeof item === 'object' && !Array.isArray(item);
}
const testNameToKey = (testName, count) => `${testName} ${count}`;
exports.testNameToKey = testNameToKey;
const keyToTestName = key => {
if (!/ \d+$/.test(key)) {
throw new Error('Snapshot keys must end with a number.');
}
return key.replace(/ \d+$/, '');
};
exports.keyToTestName = keyToTestName;
const getSnapshotData = (snapshotPath, update) => {
const data = Object.create(null);
let snapshotContents = '';
let dirty = false;
if (jestExistsFile(snapshotPath)) {
try {
snapshotContents = jestReadFile(snapshotPath, 'utf8');
// eslint-disable-next-line no-new-func
const populate = new Function('exports', snapshotContents);
populate(data);
} catch {}
}
const validationResult = validateSnapshotVersion(snapshotContents);
const isInvalid = snapshotContents && validationResult;
if (update === 'none' && isInvalid) {
throw validationResult;
}
if ((update === 'all' || update === 'new') && isInvalid) {
dirty = true;
}
return {
data,
dirty
};
};
// Add extra line breaks at beginning and end of multiline snapshot
// to make the content easier to read.
exports.getSnapshotData = getSnapshotData;
const addExtraLineBreaks = string =>
string.includes('\n') ? `\n${string}\n` : string;
// Remove extra line breaks at beginning and end of multiline snapshot.
// Instead of trim, which can remove additional newlines or spaces
// at beginning or end of the content from a custom serializer.
exports.addExtraLineBreaks = addExtraLineBreaks;
const removeExtraLineBreaks = string =>
string.length > 2 && string.startsWith('\n') && string.endsWith('\n')
? string.slice(1, -1)
: string;
exports.removeExtraLineBreaks = removeExtraLineBreaks;
const removeLinesBeforeExternalMatcherTrap = stack => {
const lines = stack.split('\n');
for (let i = 0; i < lines.length; i += 1) {
// It's a function name specified in `packages/expect/src/index.ts`
// for external custom matchers.
if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__')) {
return lines.slice(i + 1).join('\n');
}
}
return stack;
};
exports.removeLinesBeforeExternalMatcherTrap =
removeLinesBeforeExternalMatcherTrap;
const escapeRegex = true;
const printFunctionName = false;
const serialize = (val, indent = 2, formatOverrides = {}) =>
normalizeNewlines(
(0, _prettyFormat.format)(val, {
escapeRegex,
indent,
plugins: (0, _plugins.getSerializers)(),
printFunctionName,
...formatOverrides
})
);
exports.serialize = serialize;
const minify = val =>
(0, _prettyFormat.format)(val, {
escapeRegex,
min: true,
plugins: (0, _plugins.getSerializers)(),
printFunctionName
});
// Remove double quote marks and unescape double quotes and backslashes.
exports.minify = minify;
const deserializeString = stringified =>
stringified.slice(1, -1).replace(/\\("|\\)/g, '$1');
exports.deserializeString = deserializeString;
const escapeBacktickString = str => str.replace(/`|\\|\${/g, '\\$&');
exports.escapeBacktickString = escapeBacktickString;
const printBacktickString = str => `\`${escapeBacktickString(str)}\``;
const ensureDirectoryExists = filePath => {
try {
fs.mkdirSync(path.dirname(filePath), {
recursive: true
});
} catch {}
};
exports.ensureDirectoryExists = ensureDirectoryExists;
const normalizeNewlines = string => string.replace(/\r\n|\r/g, '\n');
const saveSnapshotFile = (snapshotData, snapshotPath) => {
const snapshots = Object.keys(snapshotData)
.sort(_naturalCompare.default)
.map(
key =>
`exports[${printBacktickString(key)}] = ${printBacktickString(
normalizeNewlines(snapshotData[key])
)};`
);
ensureDirectoryExists(snapshotPath);
jestWriteFile(
snapshotPath,
`${writeSnapshotVersion()}\n\n${snapshots.join('\n\n')}\n`
);
};
exports.saveSnapshotFile = saveSnapshotFile;
const isAnyOrAnything = input =>
'$$typeof' in input &&
input.$$typeof === Symbol.for('jest.asymmetricMatcher') &&
['Any', 'Anything'].includes(input.constructor.name);
const deepMergeArray = (target, source) => {
const mergedOutput = Array.from(target);
source.forEach((sourceElement, index) => {
const targetElement = mergedOutput[index];
if (Array.isArray(target[index]) && Array.isArray(sourceElement)) {
mergedOutput[index] = deepMergeArray(target[index], sourceElement);
} else if (isObject(targetElement) && !isAnyOrAnything(sourceElement)) {
mergedOutput[index] = deepMerge(target[index], sourceElement);
} else {
// Source does not exist in target or target is primitive and cannot be deep merged
mergedOutput[index] = sourceElement;
}
});
return mergedOutput;
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const deepMerge = (target, source) => {
if (isObject(target) && isObject(source)) {
const mergedOutput = {
...target
};
Object.keys(source).forEach(key => {
if (isObject(source[key]) && !source[key].$$typeof) {
if (!(key in target))
Object.assign(mergedOutput, {
[key]: source[key]
});
else mergedOutput[key] = deepMerge(target[key], source[key]);
} else if (Array.isArray(source[key])) {
mergedOutput[key] = deepMergeArray(target[key], source[key]);
} else {
Object.assign(mergedOutput, {
[key]: source[key]
});
}
});
return mergedOutput;
} else if (Array.isArray(target) && Array.isArray(source)) {
return deepMergeArray(target, source);
}
return target;
};
exports.deepMerge = deepMerge;