Updating NPM dependencies

This commit is contained in:
Drew Heavner
2020-11-11 13:30:52 +00:00
committed by GitHub
parent 7a6fb66c63
commit bd487ef324
9068 changed files with 1400893 additions and 587661 deletions

View File

@@ -4,10 +4,10 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Frame } from 'jest-message-util';
import type { Frame } from 'jest-message-util';
import type { BabelTraverse, Prettier } from './types';
export declare type InlineSnapshot = {
snapshot: string;
frame: Frame;
};
export declare const saveInlineSnapshots: (snapshots: InlineSnapshot[], prettier: any, babelTraverse: Function) => void;
//# sourceMappingURL=inline_snapshots.d.ts.map
export declare function saveInlineSnapshots(snapshots: Array<InlineSnapshot>, prettier: Prettier | null, babelTraverse: BabelTraverse): void;

View File

@@ -3,66 +3,73 @@
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.saveInlineSnapshots = void 0;
exports.saveInlineSnapshots = saveInlineSnapshots;
var _fs = _interopRequireDefault(require('fs'));
var _path = _interopRequireDefault(require('path'));
var _semver = _interopRequireDefault(require('semver'));
var path = _interopRequireWildcard(require('path'));
var _types = require('@babel/types');
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};
}
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
var jestWriteFile =
global[Symbol.for('jest-native-write-file')] || _fs.default.writeFileSync;
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (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];
}
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return obj;
return newObj;
}
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var jestWriteFile =
global[Symbol.for('jest-native-write-file')] || fs.writeFileSync;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var jestReadFile =
global[Symbol.for('jest-native-read-file')] || _fs.default.readFileSync;
global[Symbol.for('jest-native-read-file')] || fs.readFileSync;
const saveInlineSnapshots = (snapshots, prettier, babelTraverse) => {
function saveInlineSnapshots(snapshots, prettier, babelTraverse) {
if (!prettier) {
throw new Error(
`Jest: Inline Snapshots requires Prettier.\n` +
@@ -79,10 +86,7 @@ const saveInlineSnapshots = (snapshots, prettier, babelTraverse) => {
const snapshotsByFile = groupSnapshotsByFile(snapshots);
var _arr = Object.keys(snapshotsByFile);
for (var _i = 0; _i < _arr.length; _i++) {
const sourceFilePath = _arr[_i];
for (const sourceFilePath of Object.keys(snapshotsByFile)) {
saveSnapshotsForFile(
snapshotsByFile[sourceFilePath],
sourceFilePath,
@@ -90,9 +94,7 @@ const saveInlineSnapshots = (snapshots, prettier, babelTraverse) => {
babelTraverse
);
}
};
exports.saveInlineSnapshots = saveInlineSnapshots;
}
const saveSnapshotsForFile = (
snapshots,
@@ -109,29 +111,38 @@ const saveSnapshotsForFile = (
})
: null; // Detect the parser for the test file.
// For older versions of Prettier, fallback to a simple parser detection.
// @ts-expect-error
const inferredParser = prettier.getFileInfo
? prettier.getFileInfo.sync(sourceFilePath).inferredParser
: (config && config.parser) || simpleDetectParser(sourceFilePath); // Insert snapshots using the custom parser API. After insertion, the code is
: (config && config.parser) || simpleDetectParser(sourceFilePath); // Record the matcher names seen in insertion parser and pass them down one
// by one to formatting parser.
const snapshotMatcherNames = []; // Insert snapshots using the custom parser API. After insertion, 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).
const newSourceFile = prettier.format(
sourceFile,
_objectSpread({}, config, {
filepath: sourceFilePath,
parser: createInsertionParser(snapshots, inferredParser, babelTraverse)
})
); // Format the snapshots using the custom parser API.
const newSourceFile = prettier.format(sourceFile, {
...config,
filepath: sourceFilePath,
parser: createInsertionParser(
snapshots,
snapshotMatcherNames,
inferredParser,
babelTraverse
)
}); // Format the snapshots using the custom parser API.
const formattedNewSourceFile = prettier.format(
newSourceFile,
_objectSpread({}, config, {
filepath: sourceFilePath,
parser: createFormattingParser(inferredParser, babelTraverse)
})
);
const formattedNewSourceFile = prettier.format(newSourceFile, {
...config,
filepath: sourceFilePath,
parser: createFormattingParser(
snapshotMatcherNames,
inferredParser,
babelTraverse
)
});
if (formattedNewSourceFile !== sourceFile) {
jestWriteFile(sourceFilePath, formattedNewSourceFile);
@@ -141,9 +152,7 @@ const saveSnapshotsForFile = (
const groupSnapshotsBy = createKey => snapshots =>
snapshots.reduce((object, inlineSnapshot) => {
const key = createKey(inlineSnapshot);
return _objectSpread({}, object, {
[key]: (object[key] || []).concat(inlineSnapshot)
});
return {...object, [key]: (object[key] || []).concat(inlineSnapshot)};
}, {});
const groupSnapshotsByFrame = groupSnapshotsBy(({frame: {line, column}}) =>
@@ -154,7 +163,7 @@ const groupSnapshotsByFrame = groupSnapshotsBy(({frame: {line, column}}) =>
const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file);
const indent = (snapshot, numIndents, indentation) => {
const lines = snapshot.split('\n'); // Prevent re-identation of inline snapshots.
const lines = snapshot.split('\n'); // Prevent re-indentation of inline snapshots.
if (
lines.length >= 2 &&
@@ -195,11 +204,12 @@ const getAst = (parsers, inferredParser, text) => {
return ast;
}; // This parser inserts snapshots into the AST.
const createInsertionParser = (snapshots, inferredParser, babelTraverse) => (
text,
parsers,
options
) => {
const createInsertionParser = (
snapshots,
snapshotMatcherNames,
inferredParser,
babelTraverse
) => (text, parsers, options) => {
// Workaround for https://github.com/prettier/prettier/issues/3150
options.parser = inferredParser;
const groupedSnapshots = groupSnapshotsByFrame(snapshots);
@@ -209,14 +219,13 @@ const createInsertionParser = (snapshots, inferredParser, babelTraverse) => (
CallExpression({node: {arguments: args, callee}}) {
if (
callee.type !== 'MemberExpression' ||
callee.property.type !== 'Identifier'
callee.property.type !== 'Identifier' ||
callee.property.loc == null
) {
return;
}
const _callee$property$loc$ = callee.property.loc.start,
line = _callee$property$loc$.line,
column = _callee$property$loc$.column;
const {line, column} = callee.property.loc.start;
const snapshotsForFrame = groupedSnapshots[`${line}:${column}`];
if (!snapshotsForFrame) {
@@ -229,6 +238,7 @@ const createInsertionParser = (snapshots, inferredParser, babelTraverse) => (
);
}
snapshotMatcherNames.push(callee.property.name);
const snapshotIndex = args.findIndex(
({type}) => type === 'TemplateLiteral'
);
@@ -260,20 +270,22 @@ const createInsertionParser = (snapshots, inferredParser, babelTraverse) => (
return ast;
}; // This parser formats snapshots to the correct indentation.
const createFormattingParser = (inferredParser, babelTraverse) => (
text,
parsers,
options
) => {
const createFormattingParser = (
snapshotMatcherNames,
inferredParser,
babelTraverse
) => (text, parsers, options) => {
// Workaround for https://github.com/prettier/prettier/issues/3150
options.parser = inferredParser;
const ast = getAst(parsers, inferredParser, text);
babelTraverse(ast, {
CallExpression({node: {arguments: args, callee}}) {
var _options$tabWidth, _options$tabWidth2;
if (
callee.type !== 'MemberExpression' ||
callee.property.type !== 'Identifier' ||
callee.property.name !== 'toMatchInlineSnapshot' ||
!snapshotMatcherNames.includes(callee.property.name) ||
!callee.loc ||
callee.computed
) {
@@ -301,10 +313,21 @@ const createFormattingParser = (inferredParser, babelTraverse) => (
snapshot,
Math.ceil(
useSpaces
? callee.loc.start.column / options.tabWidth
? callee.loc.start.column /
((_options$tabWidth = options.tabWidth) !== null &&
_options$tabWidth !== void 0
? _options$tabWidth
: 1)
: callee.loc.start.column / 2 // Each tab is 2 characters.
),
useSpaces ? ' '.repeat(options.tabWidth) : '\t'
useSpaces
? ' '.repeat(
(_options$tabWidth2 = options.tabWidth) !== null &&
_options$tabWidth2 !== void 0
? _options$tabWidth2
: 1
)
: '\t'
);
const replacementNode = (0, _types.templateLiteral)(
[
@@ -321,11 +344,11 @@ const createFormattingParser = (inferredParser, babelTraverse) => (
};
const simpleDetectParser = filePath => {
const extname = _path.default.extname(filePath);
const extname = path.extname(filePath);
if (/tsx?$/.test(extname)) {
return 'typescript';
}
return 'babylon';
return 'babel';
};

View File

@@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Config } from '@jest/types';
import type { Config } from '@jest/types';
export declare type SnapshotResolver = {
testPathForConsistencyCheck: string;
resolveSnapshotPath(testPath: Config.Path, extension?: string): Config.Path;
@@ -14,4 +14,3 @@ export declare const EXTENSION = "snap";
export declare const DOT_EXTENSION: string;
export declare const isSnapshotPath: (path: string) => boolean;
export declare const buildSnapshotResolver: (config: Config.ProjectConfig) => SnapshotResolver;
//# sourceMappingURL=snapshot_resolver.d.ts.map

View File

@@ -5,7 +5,7 @@ Object.defineProperty(exports, '__esModule', {
});
exports.buildSnapshotResolver = exports.isSnapshotPath = exports.DOT_EXTENSION = exports.EXTENSION = void 0;
var _path = _interopRequireDefault(require('path'));
var path = _interopRequireWildcard(require('path'));
var _chalk = _interopRequireDefault(require('chalk'));
@@ -13,6 +13,48 @@ function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (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) Facebook, Inc. and its affiliates. All Rights Reserved.
*
@@ -50,17 +92,17 @@ function createSnapshotResolver(snapshotResolverPath) {
function createDefaultSnapshotResolver() {
return {
resolveSnapshotPath: testPath =>
_path.default.join(
_path.default.join(_path.default.dirname(testPath), '__snapshots__'),
_path.default.basename(testPath) + DOT_EXTENSION
path.join(
path.join(path.dirname(testPath), '__snapshots__'),
path.basename(testPath) + DOT_EXTENSION
),
resolveTestPath: snapshotPath =>
_path.default.resolve(
_path.default.dirname(snapshotPath),
path.resolve(
path.dirname(snapshotPath),
'..',
_path.default.basename(snapshotPath, DOT_EXTENSION)
path.basename(snapshotPath, DOT_EXTENSION)
),
testPathForConsistencyCheck: _path.default.posix.join(
testPathForConsistencyCheck: path.posix.join(
'consistency_check',
'__tests__',
'example.test.js'

View File

@@ -4,20 +4,33 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Config } from '@jest/types';
import type { Config } from '@jest/types';
import type { BabelTraverse, Prettier } from './types';
export declare type SnapshotStateOptions = {
updateSnapshot: Config.SnapshotUpdateState;
getPrettier: () => null | any;
getBabelTraverse: () => Function;
getPrettier: () => null | Prettier;
getBabelTraverse: () => BabelTraverse;
expand?: boolean;
};
export declare type SnapshotMatchOptions = {
testName: string;
received: any;
received: unknown;
key?: string;
inlineSnapshot?: string;
isInline: boolean;
error?: Error;
};
declare type SnapshotReturnOptions = {
actual: string;
count: number;
expected?: string;
key: string;
pass: boolean;
};
declare type SaveStatus = {
deleted: boolean;
saved: boolean;
};
export default class SnapshotState {
private _counters;
private _dirty;
@@ -39,20 +52,11 @@ export default class SnapshotState {
markSnapshotsAsCheckedForTest(testName: string): void;
private _addSnapshot;
clear(): void;
save(): {
deleted: boolean;
saved: boolean;
};
save(): SaveStatus;
getUncheckedCount(): number;
getUncheckedKeys(): Array<string>;
removeUncheckedKeys(): void;
match({ testName, received, key, inlineSnapshot, error, }: SnapshotMatchOptions): {
actual: string;
count: number;
expected: string | null;
key: string;
pass: boolean;
};
fail(testName: string, _received: any, key?: string): string;
match({ testName, received, key, inlineSnapshot, isInline, error, }: SnapshotMatchOptions): SnapshotReturnOptions;
fail(testName: string, _received: unknown, key?: string): string;
}
//# sourceMappingURL=State.d.ts.map
export {};

View File

@@ -1 +0,0 @@
{"version":3,"file":"State.d.ts","sourceRoot":"","sources":["../src/State.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAcnC,oBAAY,oBAAoB,GAAG;IACjC,cAAc,EAAE,MAAM,CAAC,mBAAmB,CAAC;IAC3C,WAAW,EAAE,MAAM,IAAI,GAAG,GAAG,CAAC;IAC9B,gBAAgB,EAAE,MAAM,QAAQ,CAAC;IACjC,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF,oBAAY,oBAAoB,GAAG;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,GAAG,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,KAAK,CAAC;CACf,CAAC;AAEF,MAAM,CAAC,OAAO,OAAO,aAAa;IAChC,OAAO,CAAC,SAAS,CAAsB;IACvC,OAAO,CAAC,MAAM,CAAU;IAExB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,eAAe,CAA6B;IACpD,OAAO,CAAC,aAAa,CAAe;IACpC,OAAO,CAAC,YAAY,CAAe;IACnC,OAAO,CAAC,aAAa,CAAc;IACnC,OAAO,CAAC,gBAAgB,CAAwB;IAChD,OAAO,CAAC,cAAc,CAAc;IACpC,OAAO,CAAC,iBAAiB,CAAiB;IAC1C,OAAO,CAAC,YAAY,CAAmB;IAEvC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;gBAEJ,YAAY,EAAE,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,oBAAoB;IAuBpE,6BAA6B,CAAC,QAAQ,EAAE,MAAM;IAQ9C,OAAO,CAAC,YAAY;IAwBpB,KAAK;IAWL,IAAI;;;;IA8BJ,iBAAiB,IAAI,MAAM;IAI3B,gBAAgB,IAAI,KAAK,CAAC,MAAM,CAAC;IAIjC,mBAAmB,IAAI,IAAI;IAQ3B,KAAK,CAAC,EACJ,QAAQ,EACR,QAAQ,EACR,GAAG,EACH,cAAc,EACd,KAAK,GACN,EAAE,oBAAoB;;;;;;;IA4FvB,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,MAAM;CAYpD"}

View File

@@ -5,23 +5,60 @@ Object.defineProperty(exports, '__esModule', {
});
exports.default = void 0;
var _fs = _interopRequireDefault(require('fs'));
var fs = _interopRequireWildcard(require('graceful-fs'));
var _jestMessageUtil = require('jest-message-util');
var _InlineSnapshots = require('./InlineSnapshots');
var _utils = require('./utils');
var _inline_snapshots = require('./inline_snapshots');
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (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 = global['jest-symbol-do-not-touch'] || global.Symbol;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var jestExistsFile =
global[Symbol.for('jest-native-exists-file')] || _fs.default.existsSync;
global[Symbol.for('jest-native-exists-file')] || fs.existsSync;
function _defineProperty(obj, key, value) {
if (key in obj) {
@@ -38,7 +75,7 @@ function _defineProperty(obj, key, value) {
}
class SnapshotState {
// @ts-ignore
// @ts-expect-error
constructor(snapshotPath, options) {
_defineProperty(this, '_counters', void 0);
@@ -73,14 +110,10 @@ class SnapshotState {
_defineProperty(this, 'updated', void 0);
this._snapshotPath = snapshotPath;
const _getSnapshotData = (0, _utils.getSnapshotData)(
this._snapshotPath,
options.updateSnapshot
),
data = _getSnapshotData.data,
dirty = _getSnapshotData.dirty;
const {data, dirty} = (0, _utils.getSnapshotData)(
this._snapshotPath,
options.updateSnapshot
);
this._initialData = data;
this._snapshotData = data;
this._dirty = dirty;
@@ -111,7 +144,9 @@ class SnapshotState {
if (options.isInline) {
const error = options.error || new Error();
const lines = (0, _jestMessageUtil.getStackTraceLines)(error.stack || '');
const lines = (0, _jestMessageUtil.getStackTraceLines)(
(0, _utils.removeLinesBeforeExternalMatcherTrap)(error.stack || '')
);
const frame = (0, _jestMessageUtil.getTopFrame)(lines);
if (!frame) {
@@ -159,7 +194,7 @@ class SnapshotState {
const babelTraverse = this._getBabelTraverse(); // Load lazily
(0, _inline_snapshots.saveInlineSnapshots)(
(0, _InlineSnapshots.saveInlineSnapshots)(
this._inlineSnapshots,
prettier,
babelTraverse
@@ -169,7 +204,7 @@ class SnapshotState {
status.saved = true;
} else if (!hasExternalSnapshots && jestExistsFile(this._snapshotPath)) {
if (this._updateSnapshot === 'all') {
_fs.default.unlinkSync(this._snapshotPath);
fs.unlinkSync(this._snapshotPath);
}
status.deleted = true;
@@ -196,11 +231,10 @@ class SnapshotState {
}
}
match({testName, received, key, inlineSnapshot, error}) {
match({testName, received, key, inlineSnapshot, isInline, error}) {
this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
const count = Number(this._counters.get(testName));
const isInline = inlineSnapshot !== undefined;
if (!key) {
key = (0, _utils.testNameToKey)(testName, count);
@@ -208,19 +242,17 @@ class SnapshotState {
// there's an external snapshot. This way the external snapshot can be
// removed with `--updateSnapshot`.
if (!(isInline && this._snapshotData[key])) {
if (!(isInline && this._snapshotData[key] !== undefined)) {
this._uncheckedKeys.delete(key);
}
const receivedSerialized = (0, _utils.serialize)(received);
const receivedSerialized = (0, _utils.addExtraLineBreaks)(
(0, _utils.serialize)(received)
);
const expected = isInline ? inlineSnapshot : this._snapshotData[key];
const pass = expected === receivedSerialized;
const hasSnapshot = isInline
? inlineSnapshot !== ''
: this._snapshotData[key] !== undefined;
const snapshotIsPersisted =
isInline || _fs.default.existsSync(this._snapshotPath);
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
@@ -278,9 +310,12 @@ class SnapshotState {
if (!pass) {
this.unmatched++;
return {
actual: (0, _utils.unescape)(receivedSerialized),
actual: (0, _utils.removeExtraLineBreaks)(receivedSerialized),
count,
expected: expected ? (0, _utils.unescape)(expected) : null,
expected:
expected !== undefined
? (0, _utils.removeExtraLineBreaks)(expected)
: undefined,
key,
pass: false
};

15
node_modules/jest-snapshot/build/colors.d.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare const aForeground2 = 90;
export declare const aBackground2 = 225;
export declare const bForeground2 = 23;
export declare const bBackground2 = 195;
export declare type RGB = [number, number, number];
export declare const aForeground3: RGB;
export declare const aBackground3: RGB;
export declare const bForeground3: RGB;
export declare const bBackground3: RGB;

30
node_modules/jest-snapshot/build/colors.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.bBackground3 = exports.bForeground3 = exports.aBackground3 = exports.aForeground3 = exports.bBackground2 = exports.bForeground2 = exports.aBackground2 = exports.aForeground2 = void 0;
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* 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;

7
node_modules/jest-snapshot/build/dedentLines.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare const dedentLines: (input: Array<string>) => Array<string> | null;

149
node_modules/jest-snapshot/build/dedentLines.js generated vendored Normal file
View File

@@ -0,0 +1,149 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.dedentLines = void 0;
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* 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

@@ -4,113 +4,27 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Config } from '@jest/types';
import { MatcherState } from 'expect';
import { SnapshotResolver as JestSnapshotResolver } from './snapshot_resolver';
import type { Config } from '@jest/types';
import type { FS as HasteFS } from 'jest-haste-map';
import { SnapshotResolver as JestSnapshotResolver } from './SnapshotResolver';
import SnapshotState from './State';
import type { Context, ExpectationResult } from './types';
import * as utils from './utils';
declare type Context = MatcherState & {
snapshotState: SnapshotState;
};
declare const JestSnapshot: {
EXTENSION: string;
SnapshotState: typeof SnapshotState;
addSerializer: (plugin: import("pretty-format/build/types").Plugin) => void;
buildSnapshotResolver: (config: Config.ProjectConfig) => JestSnapshotResolver;
cleanup: (hasteFS: import("jest-haste-map/build/HasteFS").default, update: Config.SnapshotUpdateState, snapshotResolver: JestSnapshotResolver, testPathIgnorePatterns?: string[] | undefined) => {
cleanup: (hasteFS: HasteFS, update: Config.SnapshotUpdateState, snapshotResolver: JestSnapshotResolver, testPathIgnorePatterns?: string[] | undefined) => {
filesRemoved: number;
filesRemovedList: string[];
filesRemovedList: Array<string>;
};
getSerializers: () => import("pretty-format/build/types").Plugin[];
getSerializers: () => import("pretty-format/build/types").Plugins;
isSnapshotPath: (path: string) => boolean;
toMatchInlineSnapshot: (this: Context, received: any, propertyMatchersOrInlineSnapshot?: any, inlineSnapshot?: string | undefined) => {
message: () => string;
name: string;
pass: boolean;
report: () => string;
actual?: undefined;
expected?: undefined;
} | {
message: () => string;
pass: boolean;
name?: undefined;
report?: undefined;
actual?: undefined;
expected?: undefined;
} | {
actual: string;
expected: string | null;
message: () => string;
name: string;
pass: boolean;
report: () => string;
};
toMatchSnapshot: (this: Context, received: any, propertyMatchers?: any, hint?: string | undefined) => {
message: () => string;
name: string;
pass: boolean;
report: () => string;
actual?: undefined;
expected?: undefined;
} | {
message: () => string;
pass: boolean;
name?: undefined;
report?: undefined;
actual?: undefined;
expected?: undefined;
} | {
actual: string;
expected: string | null;
message: () => string;
name: string;
pass: boolean;
report: () => string;
};
toThrowErrorMatchingInlineSnapshot: (this: Context, received: any, inlineSnapshot?: string | undefined, fromPromise?: boolean | undefined) => {
message: () => string;
name: string;
pass: boolean;
report: () => string;
actual?: undefined;
expected?: undefined;
} | {
message: () => string;
pass: boolean;
name?: undefined;
report?: undefined;
actual?: undefined;
expected?: undefined;
} | {
actual: string;
expected: string | null;
message: () => string;
name: string;
pass: boolean;
report: () => string;
};
toThrowErrorMatchingSnapshot: (this: Context, received: any, hint: string | undefined, fromPromise: boolean) => {
message: () => string;
name: string;
pass: boolean;
report: () => string;
actual?: undefined;
expected?: undefined;
} | {
message: () => string;
pass: boolean;
name?: undefined;
report?: undefined;
actual?: undefined;
expected?: undefined;
} | {
actual: string;
expected: string | null;
message: () => string;
name: string;
pass: boolean;
report: () => string;
};
toMatchInlineSnapshot: (this: Context, received: unknown, propertiesOrSnapshot?: string | object | undefined, inlineSnapshot?: string | undefined) => ExpectationResult;
toMatchSnapshot: (this: Context, received: unknown, propertiesOrHint?: string | object | undefined, hint?: string | undefined) => ExpectationResult;
toThrowErrorMatchingInlineSnapshot: (this: Context, received: unknown, inlineSnapshot?: string | undefined, fromPromise?: boolean | undefined) => ExpectationResult;
toThrowErrorMatchingSnapshot: (this: Context, received: unknown, hint: string | undefined, fromPromise: boolean) => ExpectationResult;
utils: typeof utils;
};
declare namespace JestSnapshot {
@@ -118,4 +32,3 @@ declare namespace JestSnapshot {
type SnapshotStateType = SnapshotState;
}
export = JestSnapshot;
//# sourceMappingURL=index.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAEnC,OAAO,EAAC,YAAY,EAAC,MAAM,QAAQ,CAAC;AAQpC,OAAO,EAGL,gBAAgB,IAAI,oBAAoB,EAEzC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,aAAa,MAAM,SAAS,CAAC;AAGpC,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AAEjC,aAAK,OAAO,GAAG,YAAY,GAAG;IAC5B,aAAa,EAAE,aAAa,CAAC;CAC9B,CAAC;AAidF,QAAA,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAajB,CAAC;AAEF,kBAAU,YAAY,CAAC;IACrB,KAAY,gBAAgB,GAAG,oBAAoB,CAAC;IACpD,KAAY,iBAAiB,GAAG,aAAa,CAAC;CAC/C;AAED,SAAS,YAAY,CAAC"}

View File

@@ -1,71 +1,81 @@
'use strict';
var _fs = _interopRequireDefault(require('fs'));
var fs = _interopRequireWildcard(require('graceful-fs'));
var _jestMatcherUtils = require('jest-matcher-utils');
var _snapshot_resolver = require('./snapshot_resolver');
var _SnapshotResolver = require('./SnapshotResolver');
var _State = _interopRequireDefault(require('./State'));
var _plugins = require('./plugins');
var _print = require('./print');
var _printSnapshot = require('./printSnapshot');
var utils = _interopRequireWildcard(require('./utils'));
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc =
Object.defineProperty && Object.getOwnPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: {};
if (desc.get || desc.set) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
}
newObj.default = obj;
return newObj;
}
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (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 = global['jest-symbol-do-not-touch'] || global.Symbol;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var jestExistsFile =
global[Symbol.for('jest-native-exists-file')] || _fs.default.existsSync;
global[Symbol.for('jest-native-exists-file')] || fs.existsSync;
const DID_NOT_THROW = 'Received function did not throw'; // same as toThrow
const NOT_SNAPSHOT_MATCHERS = `.${(0, _jestMatcherUtils.BOLD_WEIGHT)(
'not'
)} cannot be used with snapshot matchers`;
const HINT_ARG = 'hint';
const HINT_COLOR = _jestMatcherUtils.BOLD_WEIGHT;
const INLINE_SNAPSHOT_ARG = 'snapshot';
const PROPERTY_MATCHERS_ARG = 'properties';
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 printName = (concatenatedBlockNames = '', hint = '', count) => {
const printSnapshotName = (concatenatedBlockNames = '', hint = '', count) => {
const hasNames = concatenatedBlockNames.length !== 0;
const hasHint = hint.length !== 0;
return (
'`' +
'Snapshot name: `' +
(hasNames ? utils.escapeBacktickString(concatenatedBlockNames) : '') +
(hasNames && hasHint ? ': ' : '') +
(hasHint
@@ -123,7 +133,7 @@ const fileExists = (filePath, hasteFS) =>
hasteFS.exists(filePath) || jestExistsFile(filePath);
const cleanup = (hasteFS, update, snapshotResolver, testPathIgnorePatterns) => {
const pattern = '\\.' + _snapshot_resolver.EXTENSION + '$';
const pattern = '\\.' + _SnapshotResolver.EXTENSION + '$';
const files = hasteFS.matchFiles(pattern);
let testIgnorePatternsRegex = null;
@@ -140,7 +150,7 @@ const cleanup = (hasteFS, update, snapshotResolver, testPathIgnorePatterns) => {
if (!fileExists(testPath, hasteFS)) {
if (update === 'all') {
_fs.default.unlinkSync(snapshotFile);
fs.unlinkSync(snapshotFile);
}
return true;
@@ -154,142 +164,181 @@ const cleanup = (hasteFS, update, snapshotResolver, testPathIgnorePatterns) => {
};
};
const toMatchSnapshot = function toMatchSnapshot(
received,
propertyMatchers,
hint
) {
const toMatchSnapshot = function (received, propertiesOrHint, hint) {
const matcherName = 'toMatchSnapshot';
let expectedArgument = '';
let secondArgument = '';
let properties;
const length = arguments.length;
if (typeof propertyMatchers === 'object' && propertyMatchers !== null) {
expectedArgument = PROPERTY_MATCHERS_ARG;
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 (typeof hint === 'string' && hint.length !== 0) {
secondArgument = HINT_ARG;
}
} else if (
typeof propertyMatchers === 'string' &&
propertyMatchers.length !== 0
) {
expectedArgument = HINT_ARG;
}
if (length === 3) {
options.secondArgument = 'hint';
options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT;
const options = {
isNot: this.isNot,
promise: this.promise,
secondArgument
};
if (propertiesOrHint == null) {
printedWithType += `\n\nTo provide a hint without properties: toMatchSnapshot('hint')`;
}
}
if (expectedArgument === HINT_ARG) {
options.expectedColor = HINT_COLOR;
}
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') {}
if (secondArgument === HINT_ARG) {
options.secondArgumentColor = HINT_COLOR;
}
if (arguments.length === 3 && !propertyMatchers) {
throw new Error(
'Property matchers must be an object.\n\nTo provide a snapshot test name without property matchers, use: toMatchSnapshot("name")'
);
properties = propertiesOrHint;
}
return _toMatchSnapshot({
context: this,
expectedArgument,
hint,
isInline: false,
matcherName,
options,
propertyMatchers,
properties,
received
});
};
const toMatchInlineSnapshot = function toMatchInlineSnapshot(
const toMatchInlineSnapshot = function (
received,
propertyMatchersOrInlineSnapshot,
propertiesOrSnapshot,
inlineSnapshot
) {
const matcherName = 'toMatchInlineSnapshot';
let expectedArgument = '';
let secondArgument = '';
let properties;
const length = arguments.length;
if (typeof propertyMatchersOrInlineSnapshot === 'string') {
expectedArgument = INLINE_SNAPSHOT_ARG;
} else if (
typeof propertyMatchersOrInlineSnapshot === 'object' &&
propertyMatchersOrInlineSnapshot !== null
) {
expectedArgument = PROPERTY_MATCHERS_ARG;
if (length === 2 && typeof propertiesOrSnapshot === 'string') {
inlineSnapshot = propertiesOrSnapshot;
} else if (length >= 2) {
const options = {
isNot: this.isNot,
promise: this.promise
};
if (typeof inlineSnapshot === 'string') {
secondArgument = INLINE_SNAPSHOT_ARG;
if (length === 3) {
options.secondArgument = _printSnapshot.SNAPSHOT_ARG;
options.secondArgumentColor = _printSnapshot.noColor;
}
}
const options = {
isNot: this.isNot,
promise: this.promise,
secondArgument
};
let propertyMatchers;
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 (typeof propertyMatchersOrInlineSnapshot === 'string') {
inlineSnapshot = propertyMatchersOrInlineSnapshot;
} else {
propertyMatchers = propertyMatchersOrInlineSnapshot;
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,
expectedArgument,
inlineSnapshot: stripAddedIndentation(inlineSnapshot || ''),
inlineSnapshot:
inlineSnapshot !== undefined
? stripAddedIndentation(inlineSnapshot)
: undefined,
isInline: true,
matcherName,
options,
propertyMatchers,
properties,
received
});
};
const _toMatchSnapshot = ({
context,
expectedArgument,
hint,
inlineSnapshot,
matcherName,
options,
propertyMatchers,
received
}) => {
const _toMatchSnapshot = config => {
const {
context,
hint,
inlineSnapshot,
isInline,
matcherName,
properties
} = config;
let {received} = config;
context.dontThrow && context.dontThrow();
hint = typeof propertyMatchers === 'string' ? propertyMatchers : hint;
const currentTestName = context.currentTestName,
isNot = context.isNot,
snapshotState = context.snapshotState;
const {currentTestName, isNot, snapshotState} = context;
if (isNot) {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
expectedArgument,
options
) +
'\n\n' +
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _printSnapshot.matcherHintFromConfig)(config, false),
NOT_SNAPSHOT_MATCHERS
)
);
}
if (!snapshotState) {
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, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
expectedArgument,
options
) + '\n\nsnapshot state must be initialized'
(0, _printSnapshot.matcherHintFromConfig)(config, false) +
'\n\n' +
`Snapshot state must be initialized` +
'\n\n' +
(0, _jestMatcherUtils.printWithType)(
'Snapshot state',
snapshotState,
_jestMatcherUtils.stringify
)
);
}
@@ -298,12 +347,25 @@ const _toMatchSnapshot = ({
? `${currentTestName}: ${hint}`
: currentTestName || ''; // future BREAKING change: || hint
if (typeof propertyMatchers === 'object') {
if (propertyMatchers === null) {
throw new Error(`Property matchers must be an object.`);
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, propertyMatchers, [
const propertyPass = context.equals(received, properties, [
context.utils.iterableEquality,
context.utils.subsetEquality
]);
@@ -313,176 +375,192 @@ const _toMatchSnapshot = ({
const matched = /(\d+)$/.exec(key);
const count = matched === null ? 1 : Number(matched[1]);
const report = () =>
`Snapshot name: ${printName(currentTestName, hint, count)}\n` +
'\n' +
`Expected properties: ${context.utils.printExpected(
propertyMatchers
)}\n` +
`Received value: ${context.utils.printReceived(received)}`;
const message = () =>
(0, _printSnapshot.matcherHintFromConfig)(config, false) +
'\n\n' +
printSnapshotName(currentTestName, hint, count) +
'\n\n' +
(0, _printSnapshot.printPropertiesAndReceived)(
properties,
received,
snapshotState.expand
);
return {
message: () =>
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
expectedArgument,
options
) +
'\n\n' +
report(),
message,
name: matcherName,
pass: false,
report
pass: false
};
} else {
received = utils.deepMerge(received, propertyMatchers);
received = utils.deepMerge(received, properties);
}
}
const result = snapshotState.match({
error: context.error,
inlineSnapshot,
isInline,
received,
testName: fullTestName
});
const count = result.count,
pass = result.pass;
let actual = result.actual,
expected = result.expected;
let report;
const {actual, count, expected, pass} = result;
if (pass) {
return {
message: () => '',
pass: true
};
} else if (!expected) {
report = () =>
`New snapshot was ${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'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` +
`${(0, _jestMatcherUtils.RECEIVED_COLOR)('Received value')} ` +
`${actual}`;
} else {
expected = (expected || '').trim();
actual = (actual || '').trim(); // Assign to local variable because of declaration let expected:
// TypeScript thinks it could change before report function is called.
}
const printed = (0, _print.printDiffOrStringified)(
expected,
actual,
received,
'Snapshot',
'Received',
snapshotState.expand
);
report = () =>
`Snapshot name: ${printName(currentTestName, hint, count)}\n\n` + printed;
} // Passing the actual and expected objects so that a custom reporter
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
); // 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: () =>
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
expectedArgument,
options
) +
'\n\n' +
report(),
message,
name: matcherName,
pass: false,
report
pass: false
};
};
const toThrowErrorMatchingSnapshot = function toThrowErrorMatchingSnapshot(
const toThrowErrorMatchingSnapshot = function (
received,
hint, // because error TS1016 for hint?: string
fromPromise
) {
const matcherName = 'toThrowErrorMatchingSnapshot';
const expectedArgument =
typeof hint === 'string' && hint.length !== 0 ? HINT_ARG : '';
const options = {
expectedColor: HINT_COLOR,
isNot: this.isNot,
promise: this.promise,
secondArgument: ''
};
const matcherName = 'toThrowErrorMatchingSnapshot'; // Future breaking change: Snapshot hint must be a string
// if (hint !== undefined && typeof hint !== string) {}
return _toThrowErrorMatchingSnapshot(
{
context: this,
expectedArgument,
hint,
isInline: false,
matcherName,
options,
received
},
fromPromise
);
};
const toThrowErrorMatchingInlineSnapshot = function toThrowErrorMatchingInlineSnapshot(
const toThrowErrorMatchingInlineSnapshot = function (
received,
inlineSnapshot,
fromPromise
) {
const matcherName = 'toThrowErrorMatchingInlineSnapshot';
const expectedArgument =
typeof inlineSnapshot === 'string' ? INLINE_SNAPSHOT_ARG : '';
const options = {
isNot: this.isNot,
promise: this.promise,
secondArgument: ''
};
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,
expectedArgument,
inlineSnapshot: inlineSnapshot || '',
inlineSnapshot:
inlineSnapshot !== undefined
? stripAddedIndentation(inlineSnapshot)
: undefined,
isInline: true,
matcherName,
options,
received
},
fromPromise
);
};
const _toThrowErrorMatchingSnapshot = (
{
const _toThrowErrorMatchingSnapshot = (config, fromPromise) => {
const {
context,
expectedArgument,
hint,
inlineSnapshot,
isInline,
matcherName,
options,
received,
hint
},
fromPromise
) => {
received
} = config;
context.dontThrow && context.dontThrow();
const isNot = context.isNot;
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.matcherHint)(
matcherName,
undefined,
expectedArgument,
options
) +
'\n\n' +
(0, _jestMatcherUtils.matcherErrorMessage)(
(0, _printSnapshot.matcherHintFromConfig)(config, false),
NOT_SNAPSHOT_MATCHERS
)
);
}
@@ -499,13 +577,9 @@ const _toThrowErrorMatchingSnapshot = (
}
if (error === undefined) {
// Because the received value is a function, this is not a matcher error.
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
matcherName,
undefined,
expectedArgument,
options
) +
(0, _printSnapshot.matcherHintFromConfig)(config, false) +
'\n\n' +
DID_NOT_THROW
);
@@ -513,29 +587,26 @@ const _toThrowErrorMatchingSnapshot = (
return _toMatchSnapshot({
context,
expectedArgument,
hint,
inlineSnapshot,
isInline,
matcherName,
options,
received: error.message
});
};
const JestSnapshot = {
EXTENSION: _snapshot_resolver.EXTENSION,
EXTENSION: _SnapshotResolver.EXTENSION,
SnapshotState: _State.default,
addSerializer: _plugins.addSerializer,
buildSnapshotResolver: _snapshot_resolver.buildSnapshotResolver,
buildSnapshotResolver: _SnapshotResolver.buildSnapshotResolver,
cleanup,
getSerializers: _plugins.getSerializers,
isSnapshotPath: _snapshot_resolver.isSnapshotPath,
isSnapshotPath: _SnapshotResolver.isSnapshotPath,
toMatchInlineSnapshot,
toMatchSnapshot,
toThrowErrorMatchingInlineSnapshot,
toThrowErrorMatchingSnapshot,
utils
};
/* eslint-disable-next-line no-redeclare */
module.exports = JestSnapshot;

View File

@@ -1 +0,0 @@
{"version":3,"file":"inline_snapshots.d.ts","sourceRoot":"","sources":["../src/inline_snapshots.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,EAAC,KAAK,EAAC,MAAM,mBAAmB,CAAC;AAKxC,oBAAY,cAAc,GAAG;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;CACd,CAAC;AAEF,eAAO,MAAM,mBAAmB,+EA8B/B,CAAC"}

View File

@@ -4,9 +4,8 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { NewPlugin } from 'pretty-format';
import type { NewPlugin } from 'pretty-format';
export declare const serialize: NewPlugin['serialize'];
export declare const test: NewPlugin['test'];
declare const plugin: NewPlugin;
export default plugin;
//# sourceMappingURL=mock_serializer.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"mock_serializer.d.ts","sourceRoot":"","sources":["../src/mock_serializer.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAC,SAAS,EAAC,MAAM,eAAe,CAAC;AAExC,eAAO,MAAM,SAAS,EAAE,SAAS,CAAC,WAAW,CAiC5C,CAAC;AAEF,eAAO,MAAM,IAAI,EAAE,SAAS,CAAC,MAAM,CAAuC,CAAC;AAE3E,QAAA,MAAM,MAAM,EAAE,SAA6B,CAAC;AAE5C,eAAe,MAAM,CAAC"}

View File

@@ -4,6 +4,6 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare const addSerializer: (plugin: import("pretty-format/build/types").Plugin) => void;
export declare const getSerializers: () => import("pretty-format/build/types").Plugin[];
//# sourceMappingURL=plugins.d.ts.map
import prettyFormat = require('pretty-format');
export declare const addSerializer: (plugin: prettyFormat.Plugin) => void;
export declare const getSerializers: () => import("pretty-format/build/types").Plugins;

View File

@@ -1 +0,0 @@
{"version":3,"file":"plugins.d.ts","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA0BH,eAAO,MAAM,aAAa,8DAEzB,CAAC;AAEF,eAAO,MAAM,cAAc,oDAAgB,CAAC"}

View File

@@ -7,7 +7,7 @@ exports.getSerializers = exports.addSerializer = void 0;
var _prettyFormat = _interopRequireDefault(require('pretty-format'));
var _mock_serializer = _interopRequireDefault(require('./mock_serializer'));
var _mockSerializer = _interopRequireDefault(require('./mockSerializer'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
@@ -19,20 +19,21 @@ function _interopRequireDefault(obj) {
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const _prettyFormat$plugins = _prettyFormat.default.plugins,
DOMCollection = _prettyFormat$plugins.DOMCollection,
DOMElement = _prettyFormat$plugins.DOMElement,
Immutable = _prettyFormat$plugins.Immutable,
ReactElement = _prettyFormat$plugins.ReactElement,
ReactTestComponent = _prettyFormat$plugins.ReactTestComponent,
AsymmetricMatcher = _prettyFormat$plugins.AsymmetricMatcher;
const {
DOMCollection,
DOMElement,
Immutable,
ReactElement,
ReactTestComponent,
AsymmetricMatcher
} = _prettyFormat.default.plugins;
let PLUGINS = [
ReactTestComponent,
ReactElement,
DOMElement,
DOMCollection,
Immutable,
_mock_serializer.default,
_mockSerializer.default,
AsymmetricMatcher
]; // Prepend to list so the last added is the first tested.

View File

@@ -1,8 +0,0 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare const printDiffOrStringified: (expectedSerializedTrimmed: string, receivedSerializedTrimmed: string, received: unknown, expectedLabel: string, receivedLabel: string, expand: boolean) => string;
//# sourceMappingURL=print.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"print.d.ts","sourceRoot":"","sources":["../src/print.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA0CH,eAAO,MAAM,sBAAsB,oKAkFlC,CAAC"}

View File

@@ -1,174 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.printDiffOrStringified = void 0;
var _jestDiff = _interopRequireWildcard(require('jest-diff'));
var _jestGetType = _interopRequireWildcard(require('jest-get-type'));
var _jestMatcherUtils = require('jest-matcher-utils');
var _prettyFormat = _interopRequireDefault(require('pretty-format'));
var _utils = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc =
Object.defineProperty && Object.getOwnPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: {};
if (desc.get || desc.set) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
}
newObj.default = obj;
return newObj;
}
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const isLineDiffable = received => {
const receivedType = (0, _jestGetType.default)(received);
if ((0, _jestGetType.isPrimitive)(received)) {
return typeof received === 'string' && received.includes('\n');
}
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 printDiffOrStringified = (
expectedSerializedTrimmed,
receivedSerializedTrimmed,
received,
expectedLabel,
receivedLabel,
expand
) => {
if (typeof received === 'string') {
if (
expectedSerializedTrimmed.length >= 2 &&
expectedSerializedTrimmed.startsWith('"') &&
expectedSerializedTrimmed.endsWith('"') &&
receivedSerializedTrimmed ===
(0, _utils.unescape)((0, _prettyFormat.default)(received))
) {
// The expected snapshot looks like a stringified string.
// The received serialization is default stringified string.
// Undo default serialization of expected snapshot:
// Remove enclosing double quote marks.
// Remove backslash escape preceding backslash here,
// because unescape replaced it only preceding double quote mark.
return (0, _jestMatcherUtils.printDiffOrStringify)(
expectedSerializedTrimmed.slice(1, -1).replace(/\\\\/g, '\\'),
received,
expectedLabel,
receivedLabel,
expand
);
} // Display substring highlight even when strings have custom serialization.
const result = (0, _jestDiff.getStringDiff)(
expectedSerializedTrimmed,
receivedSerializedTrimmed,
{
aAnnotation: expectedLabel,
bAnnotation: receivedLabel,
expand
}
);
if (result !== null) {
if (result.isMultiline) {
return result.annotatedDiff;
} // Because not default stringify, call EXPECTED_COLOR and RECEIVED_COLOR
// This is reason to call getStringDiff instead of printDiffOrStringify
// Because there is no closing double quote mark at end of single lines,
// future improvement is to call replaceSpacesAtEnd if it becomes public.
const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
expectedLabel,
receivedLabel
);
return (
printLabel(expectedLabel) +
(0, _jestMatcherUtils.EXPECTED_COLOR)(result.a) +
'\n' +
printLabel(receivedLabel) +
(0, _jestMatcherUtils.RECEIVED_COLOR)(result.b)
);
}
}
if (
(expectedSerializedTrimmed.includes('\n') ||
receivedSerializedTrimmed.includes('\n')) &&
isLineDiffable(received)
) {
return (0, _jestDiff.default)(
expectedSerializedTrimmed,
receivedSerializedTrimmed,
{
aAnnotation: expectedLabel,
bAnnotation: receivedLabel,
expand
}
);
}
const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(
expectedLabel,
receivedLabel
);
return (
printLabel(expectedLabel) +
(0, _jestMatcherUtils.EXPECTED_COLOR)(expectedSerializedTrimmed) +
'\n' +
printLabel(receivedLabel) +
(0, _jestMatcherUtils.RECEIVED_COLOR)(receivedSerializedTrimmed)
);
};
exports.printDiffOrStringified = printDiffOrStringified;

24
node_modules/jest-snapshot/build/printSnapshot.d.ts generated vendored Normal file
View File

@@ -0,0 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk = require('chalk');
import { DiffOptionsColor } from 'jest-diff';
import type { MatchSnapshotConfig } from './types';
declare type Chalk = chalk.Chalk;
export declare const getSnapshotColorForChalkInstance: (chalkInstance: Chalk) => DiffOptionsColor;
export declare const getReceivedColorForChalkInstance: (chalkInstance: Chalk) => DiffOptionsColor;
export declare const aSnapshotColor: DiffOptionsColor;
export declare const bReceivedColor: DiffOptionsColor;
export declare const noColor: (string: string) => string;
export declare const HINT_ARG = "hint";
export declare const SNAPSHOT_ARG = "snapshot";
export declare const PROPERTIES_ARG = "properties";
export declare const matcherHintFromConfig: ({ context: { isNot, promise }, hint, inlineSnapshot, matcherName, properties, }: MatchSnapshotConfig, isUpdatable: boolean) => string;
export declare const printExpected: (val: unknown) => string;
export declare const printReceived: (val: unknown) => string;
export declare const printPropertiesAndReceived: (properties: object, received: object, expand: boolean) => string;
export declare const printSnapshotAndReceived: (a: string, b: string, received: unknown, expand: boolean) => string;
export {};

384
node_modules/jest-snapshot/build/printSnapshot.js generated vendored Normal file
View File

@@ -0,0 +1,384 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.printSnapshotAndReceived = exports.printPropertiesAndReceived = exports.printReceived = exports.printExpected = exports.matcherHintFromConfig = exports.PROPERTIES_ARG = exports.SNAPSHOT_ARG = exports.HINT_ARG = exports.noColor = exports.bReceivedColor = exports.aSnapshotColor = exports.getReceivedColorForChalkInstance = exports.getSnapshotColorForChalkInstance = void 0;
var _chalk = _interopRequireDefault(require('chalk'));
var _utils = require('expect/build/utils');
var _jestDiff = require('jest-diff');
var _jestGetType = _interopRequireDefault(require('jest-get-type'));
var _jestMatcherUtils = require('jest-matcher-utils');
var _prettyFormat = _interopRequireDefault(require('pretty-format'));
var _colors = require('./colors');
var _dedentLines = require('./dedentLines');
var _utils2 = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable local/ban-types-eventually */
// Temporary hack because getObjectSubset has known limitations,
// is not in the public interface of the expect package,
// and the long-term goal is to use a non-serialization diff.
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.default)(received);
if (_jestGetType.default.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, _utils2.minify)(val));
exports.printExpected = printExpected;
const printReceived = val =>
(0, _jestMatcherUtils.RECEIVED_COLOR)((0, _utils2.minify)(val));
exports.printReceived = printReceived;
const printPropertiesAndReceived = (properties, received, expand) => {
const aAnnotation = 'Expected properties';
const bAnnotation = 'Received value';
if (isLineDiffable(properties) && isLineDiffable(received)) {
return (0, _jestDiff.diffLinesUnified)(
(0, _utils2.serialize)(properties).split('\n'),
(0, _utils2.serialize)(
(0, _utils.getObjectSubset)(received, properties)
).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) => {
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.default)(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, _utils2.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, _utils2.serialize)(received, 0);
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

@@ -1 +0,0 @@
{"version":3,"file":"snapshot_resolver.d.ts","sourceRoot":"","sources":["../src/snapshot_resolver.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAGnC,oBAAY,gBAAgB,GAAG;IAC7B,2BAA2B,EAAE,MAAM,CAAC;IACpC,mBAAmB,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC;IAC5E,eAAe,CAAC,YAAY,EAAE,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC;CAC7E,CAAC;AAEF,eAAO,MAAM,SAAS,SAAS,CAAC;AAChC,eAAO,MAAM,aAAa,QAAkB,CAAC;AAE7C,eAAO,MAAM,cAAc,2BACG,CAAC;AAG/B,eAAO,MAAM,qBAAqB,oDAQjC,CAAC"}

View File

@@ -4,5 +4,24 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { MatcherState } from 'expect';
import type SnapshotState from './State';
export declare type Context = MatcherState & {
snapshotState: SnapshotState;
};
export declare type MatchSnapshotConfig = {
context: Context;
hint?: string;
inlineSnapshot?: string;
isInline: boolean;
matcherName: string;
properties?: object;
received: any;
};
export declare type SnapshotData = Record<string, string>;
//# sourceMappingURL=types.d.ts.map
export declare type ExpectationResult = {
pass: boolean;
message: () => string;
};
export declare type BabelTraverse = typeof import('@babel/traverse').default;
export declare type Prettier = typeof import('prettier');

View File

@@ -1 +0,0 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,oBAAY,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC"}

View File

@@ -4,20 +4,24 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Config } from '@jest/types';
import type { Config } from '@jest/types';
import type { SnapshotData } from './types';
export declare const SNAPSHOT_VERSION = "1";
export declare const SNAPSHOT_GUIDE_LINK = "https://goo.gl/fbAQLP";
export declare const SNAPSHOT_VERSION_WARNING: string;
export declare const testNameToKey: (testName: string, count: number) => string;
export declare const testNameToKey: (testName: Config.Path, count: number) => string;
export declare const keyToTestName: (key: string) => string;
export declare const getSnapshotData: (snapshotPath: string, update: Config.SnapshotUpdateState) => {
data: Record<string, string>;
export declare const getSnapshotData: (snapshotPath: Config.Path, update: Config.SnapshotUpdateState) => {
data: SnapshotData;
dirty: boolean;
};
export declare const serialize: (data: string) => string;
export declare const unescape: (data: string) => string;
export declare const addExtraLineBreaks: (string: string) => string;
export declare const removeExtraLineBreaks: (string: string) => string;
export declare const removeLinesBeforeExternalMatcherTrap: (stack: string) => string;
export declare const serialize: (val: unknown, indent?: number) => string;
export declare const minify: (val: unknown) => string;
export declare const deserializeString: (stringified: string) => string;
export declare const escapeBacktickString: (str: string) => string;
export declare const ensureDirectoryExists: (filePath: string) => void;
export declare const saveSnapshotFile: (snapshotData: Record<string, string>, snapshotPath: string) => void;
export declare const ensureDirectoryExists: (filePath: Config.Path) => void;
export declare const saveSnapshotFile: (snapshotData: SnapshotData, snapshotPath: Config.Path) => void;
export declare const deepMerge: (target: any, source: any) => any;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,OAAO,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AAKnC,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC,eAAO,MAAM,mBAAmB,0BAA0B,CAAC;AAC3D,eAAO,MAAM,wBAAwB,QAIpC,CAAC;AAwDF,eAAO,MAAM,aAAa,6CACF,CAAC;AAEzB,eAAO,MAAM,aAAa,yBAMzB,CAAC;AAEF,eAAO,MAAM,eAAe;;;CAgC3B,CAAC;AAOF,eAAO,MAAM,SAAS,0BASnB,CAAC;AAGJ,eAAO,MAAM,QAAQ,0BAAyD,CAAC;AAE/E,eAAO,MAAM,oBAAoB,yBACC,CAAC;AAKnC,eAAO,MAAM,qBAAqB,4BAIjC,CAAC;AAIF,eAAO,MAAM,gBAAgB,sEAoB5B,CAAC;AAqBF,eAAO,MAAM,SAAS,mCAerB,CAAC"}

View File

@@ -3,18 +3,16 @@
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.deepMerge = exports.saveSnapshotFile = exports.ensureDirectoryExists = exports.escapeBacktickString = exports.unescape = exports.serialize = exports.getSnapshotData = exports.keyToTestName = exports.testNameToKey = exports.SNAPSHOT_VERSION_WARNING = exports.SNAPSHOT_GUIDE_LINK = exports.SNAPSHOT_VERSION = void 0;
exports.deepMerge = exports.saveSnapshotFile = exports.ensureDirectoryExists = exports.escapeBacktickString = exports.deserializeString = exports.minify = exports.serialize = exports.removeLinesBeforeExternalMatcherTrap = exports.removeExtraLineBreaks = exports.addExtraLineBreaks = exports.getSnapshotData = exports.keyToTestName = exports.testNameToKey = exports.SNAPSHOT_VERSION_WARNING = exports.SNAPSHOT_GUIDE_LINK = exports.SNAPSHOT_VERSION = void 0;
var _fs = _interopRequireDefault(require('fs'));
var _path = _interopRequireDefault(require('path'));
var _mkdirp = _interopRequireDefault(require('mkdirp'));
var _naturalCompare = _interopRequireDefault(require('natural-compare'));
var path = _interopRequireWildcard(require('path'));
var _chalk = _interopRequireDefault(require('chalk'));
var fs = _interopRequireWildcard(require('graceful-fs'));
var _naturalCompare = _interopRequireDefault(require('natural-compare'));
var _prettyFormat = _interopRequireDefault(require('pretty-format'));
var _plugins = require('./plugins');
@@ -23,55 +21,58 @@ function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (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];
}
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return obj;
return newObj;
}
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var jestWriteFile =
global[Symbol.for('jest-native-write-file')] || _fs.default.writeFileSync;
global[Symbol.for('jest-native-write-file')] || fs.writeFileSync;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var jestReadFile =
global[Symbol.for('jest-native-read-file')] || _fs.default.readFileSync;
global[Symbol.for('jest-native-read-file')] || fs.readFileSync;
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var jestExistsFile =
global[Symbol.for('jest-native-exists-file')] || _fs.default.existsSync;
global[Symbol.for('jest-native-exists-file')] || fs.existsSync;
const SNAPSHOT_VERSION = '1';
exports.SNAPSHOT_VERSION = SNAPSHOT_VERSION;
const SNAPSHOT_VERSION_REGEXP = /^\/\/ Jest Snapshot v(.+),/;
@@ -171,7 +172,7 @@ const getSnapshotData = (snapshotPath, update) => {
const populate = new Function('exports', snapshotContents);
populate(data);
} catch (e) {}
} catch {}
}
const validationResult = validateSnapshotVersion(snapshotContents);
@@ -189,30 +190,69 @@ const getSnapshotData = (snapshotPath, update) => {
data,
dirty
};
}; // 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
}; // 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;
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.
const serialize = data =>
addExtraLineBreaks(
normalizeNewlines(
(0, _prettyFormat.default)(data, {
escapeRegex: true,
plugins: (0, _plugins.getSerializers)(),
printFunctionName: false
})
)
); // unescape double quotes
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) =>
normalizeNewlines(
(0, _prettyFormat.default)(val, {
escapeRegex,
indent,
plugins: (0, _plugins.getSerializers)(),
printFunctionName
})
);
exports.serialize = serialize;
const unescape = data => data.replace(/\\(")/g, '$1');
const minify = val =>
(0, _prettyFormat.default)(val, {
escapeRegex,
min: true,
plugins: (0, _plugins.getSerializers)(),
printFunctionName
}); // Remove double quote marks and unescape double quotes and backslashes.
exports.unescape = unescape;
exports.minify = minify;
const deserializeString = stringified =>
stringified.slice(1, -1).replace(/\\("|\\)/g, '$1');
exports.deserializeString = deserializeString;
const escapeBacktickString = str => str.replace(/`|\\|\${/g, '\\$&');
@@ -222,11 +262,10 @@ const printBacktickString = str => '`' + escapeBacktickString(str) + '`';
const ensureDirectoryExists = filePath => {
try {
_mkdirp.default.sync(
_path.default.join(_path.default.dirname(filePath)),
'777'
);
} catch (e) {}
fs.mkdirSync(path.join(path.dirname(filePath)), {
recursive: true
});
} catch {}
};
exports.ensureDirectoryExists = ensureDirectoryExists;
@@ -268,12 +307,11 @@ const deepMergeArray = (target, source) => {
}
});
return mergedOutput;
};
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const deepMerge = (target, source) => {
const mergedOutput = _objectSpread({}, target);
if (isObject(target) && isObject(source)) {
const mergedOutput = {...target};
Object.keys(source).forEach(key => {
if (isObject(source[key]) && !source[key].$$typeof) {
if (!(key in target))
@@ -289,9 +327,12 @@ const deepMerge = (target, source) => {
});
}
});
return mergedOutput;
} else if (Array.isArray(target) && Array.isArray(source)) {
return deepMergeArray(target, source);
}
return mergedOutput;
return target;
};
exports.deepMerge = deepMerge;