Skip to content

Commit

Permalink
Lets the user override any of the snapshot formatting options
Browse files Browse the repository at this point in the history
  • Loading branch information
orta committed Jul 12, 2021
1 parent d876255 commit f8e6d51
Show file tree
Hide file tree
Showing 13 changed files with 74 additions and 31 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`snapshot serializer prototypes for object and array: no prototypes 1`] = `
{
"array": [
{
"hello": "Danger",
},
],
}
`;
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
*/
'use strict';

describe('inline snapshot serializer', () => {
it('does not show prototypes for object and array', () => {
describe('snapshot serializer', () => {
it('does not show prototypes for object and array inline', () => {
const object = {
array: [{hello: 'Danger'}],
};
Expand All @@ -22,4 +22,11 @@ describe('inline snapshot serializer', () => {
}
`);
});

it('prototypes for object and array', () => {
const object = {
array: [{hello: 'Danger'}],
};
expect(object).toMatchSnapshot('no prototypes');
});
});
12 changes: 12 additions & 0 deletions e2e/snapshot-formatting-changes/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"jest": {
"testEnvironment": "node",
"inlineSnapshotFormat": {
"printBasicPrototype": false
},
"snapshotFormat": {
"printBasicPrototype": false,
"indent": 8
}
}
}
6 changes: 0 additions & 6 deletions e2e/snapshot-inline-basic-formatting/package.json

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,9 @@ export const initialize = async ({
const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
const snapshotState = new SnapshotState(snapshotPath, {
expand,
preferSimpleForInline: config.inlineSnapshotFormatter === 'simple',
inlineSnapshotFormat: config.inlineSnapshotFormat,
prettierPath: config.prettierPath,
snapshotFormat: config.snapshotFormat,
updateSnapshot,
});
// @ts-expect-error: snapshotState is a jest extension of `expect`
Expand Down
7 changes: 3 additions & 4 deletions packages/jest-config/src/ValidConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import type {Config} from '@jest/types';
import {replacePathSepForRegex} from 'jest-regex-util';
import {multipleValidOptions} from 'jest-validate';
import {DEFAULT_OPTIONS as PRETTY_FORMAT_DEFAULTS} from 'pretty-format';
import {NODE_MODULES} from './constants';

const NODE_MODULES_REGEXP = replacePathSepForRegex(NODE_MODULES);
Expand Down Expand Up @@ -66,10 +67,7 @@ const initialOptions: Config.InitialOptions = {
throwOnModuleCollision: false,
},
injectGlobals: true,
inlineSnapshotFormatter: multipleValidOptions(
'exposed prototypes',
'simple',
) as any,
inlineSnapshotFormat: PRETTY_FORMAT_DEFAULTS,
json: false,
lastCommit: false,
listTests: false,
Expand Down Expand Up @@ -113,6 +111,7 @@ const initialOptions: Config.InitialOptions = {
skipFilter: false,
skipNodeResolution: false,
slowTestThreshold: 5,
snapshotFormat: PRETTY_FORMAT_DEFAULTS,
snapshotResolver: '<rootDir>/snapshotResolver.js',
snapshotSerializers: ['my-serializer-module'],
testEnvironment: 'jest-environment-jsdom',
Expand Down
6 changes: 4 additions & 2 deletions packages/jest-config/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ const groupOptions = (
forceExit: options.forceExit,
globalSetup: options.globalSetup,
globalTeardown: options.globalTeardown,
inlineSnapshotFormatter: options.inlineSnapshotFormatter,
inlineSnapshotFormat: options.inlineSnapshotFormat,
json: options.json,
lastCommit: options.lastCommit,
listTests: options.listTests,
Expand All @@ -150,6 +150,7 @@ const groupOptions = (
runTestsByPath: options.runTestsByPath,
silent: options.silent,
skipFilter: options.skipFilter,
snapshotFormat: options.snapshotFormat,
testFailureExitCode: options.testFailureExitCode,
testNamePattern: options.testNamePattern,
testPathPattern: options.testPathPattern,
Expand Down Expand Up @@ -185,7 +186,7 @@ const groupOptions = (
globals: options.globals,
haste: options.haste,
injectGlobals: options.injectGlobals,
inlineSnapshotFormatter: options.inlineSnapshotFormatter,
inlineSnapshotFormat: options.inlineSnapshotFormat,
moduleDirectories: options.moduleDirectories,
moduleFileExtensions: options.moduleFileExtensions,
moduleLoader: options.moduleLoader,
Expand All @@ -206,6 +207,7 @@ const groupOptions = (
skipFilter: options.skipFilter,
skipNodeResolution: options.skipNodeResolution,
slowTestThreshold: options.slowTestThreshold,
snapshotFormat: options.snapshotFormat,
snapshotResolver: options.snapshotResolver,
snapshotSerializers: options.snapshotSerializers,
testEnvironment: options.testEnvironment,
Expand Down
3 changes: 3 additions & 0 deletions packages/jest-config/src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
tryRealpath,
} from 'jest-util';
import {ValidationError, validate} from 'jest-validate';
import {DEFAULT_OPTIONS as PRETTY_FORMAT_DEFAULTS} from 'pretty-format';
import DEFAULT_CONFIG from './Defaults';
import DEPRECATED_CONFIG from './Deprecated';
import {validateReporters} from './ReporterValidationErrors';
Expand Down Expand Up @@ -970,6 +971,7 @@ export default async function normalize(
case 'extensionsToTreatAsEsm':
case 'extraGlobals':
case 'globals':
case 'inlineSnapshotFormat':
case 'findRelatedTests':
case 'forceCoverageMatch':
case 'forceExit':
Expand Down Expand Up @@ -997,6 +999,7 @@ export default async function normalize(
case 'skipFilter':
case 'skipNodeResolution':
case 'slowTestThreshold':
case 'snapshotFormat':
case 'testEnvironment':
case 'testEnvironmentOptions':
case 'testFailureExitCode':
Expand Down
19 changes: 12 additions & 7 deletions packages/jest-snapshot/src/State.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import * as fs from 'graceful-fs';
import type {Config} from '@jest/types';
import {getStackTraceLines, getTopFrame} from 'jest-message-util';
import type {OptionsReceived as PrettyFormatOptions} from 'pretty-format';
import {InlineSnapshot, saveInlineSnapshots} from './InlineSnapshots';
import type {SnapshotData} from './types';
import {
Expand All @@ -26,6 +27,8 @@ export type SnapshotStateOptions = {
prettierPath: Config.Path;
expand?: boolean;
preferSimpleForInline?: boolean;
snapshotFormat: PrettyFormatOptions;
inlineSnapshotFormat: PrettyFormatOptions;
};

export type SnapshotMatchOptions = {
Expand Down Expand Up @@ -62,7 +65,8 @@ export default class SnapshotState {
private _inlineSnapshots: Array<InlineSnapshot>;
private _uncheckedKeys: Set<string>;
private _prettierPath: Config.Path;
private _preferSimpleInlineSnapshots: boolean;
private _snapshotFormat: PrettyFormatOptions;
private _inlineSnapshotFormat: PrettyFormatOptions;

added: number;
expand: boolean;
Expand Down Expand Up @@ -90,7 +94,9 @@ export default class SnapshotState {
this.unmatched = 0;
this._updateSnapshot = options.updateSnapshot;
this.updated = 0;
this._preferSimpleInlineSnapshots = options.preferSimpleForInline || false;

this._snapshotFormat = options.snapshotFormat;
this._inlineSnapshotFormat = options.inlineSnapshotFormat;
}

markSnapshotsAsCheckedForTest(testName: string): void {
Expand Down Expand Up @@ -204,13 +210,12 @@ export default class SnapshotState {
this._uncheckedKeys.delete(key);
}

// There is an option to allow for not showing 'Object' and 'Array' on
// snapshots, which we'd like to allow for opting into with inline snapshots.
const hasOptedInToSimpleInline =
isInline && this._preferSimpleInlineSnapshots;
const customFormat = isInline
? this._inlineSnapshotFormat
: this._snapshotFormat;

const receivedSerialized = addExtraLineBreaks(
serialize(received, undefined, hasOptedInToSimpleInline),
serialize(received, undefined, customFormat),
);
const expected = isInline ? inlineSnapshot : this._snapshotData[key];
const pass = expected === receivedSerialized;
Expand Down
9 changes: 6 additions & 3 deletions packages/jest-snapshot/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import chalk = require('chalk');
import * as fs from 'graceful-fs';
import naturalCompare = require('natural-compare');
import type {Config} from '@jest/types';
import {format as prettyFormat} from 'pretty-format';
import {
OptionsReceived as PrettyFormatOptions,
format as prettyFormat,
} from 'pretty-format';
import {getSerializers} from './plugins';
import type {SnapshotData} from './types';

Expand Down Expand Up @@ -155,15 +158,15 @@ const printFunctionName = false;
export const serialize = (
val: unknown,
indent = 2,
printBasicPrototype: boolean = true,
formatOverrides: PrettyFormatOptions = {},
): string =>
normalizeNewlines(
prettyFormat(val, {
escapeRegex,
indent,
plugins: getSerializers(),
printBasicPrototype,
printFunctionName,
...formatOverrides,
}),
);

Expand Down
10 changes: 7 additions & 3 deletions packages/jest-types/src/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import type {ForegroundColor} from 'chalk';
import type {ReportOptions} from 'istanbul-reports';
import type {Arguments} from 'yargs';
import type {OptionsReceived as PrettyFormatOptions} from 'pretty-format';

type CoverageProvider = 'babel' | 'v8';

Expand Down Expand Up @@ -171,7 +172,7 @@ export type InitialOptions = Partial<{
globalTeardown: string | null | undefined;
haste: HasteConfig;
injectGlobals: boolean;
inlineSnapshotFormatter: 'exposed prototypes' | 'simple';
inlineSnapshotFormat: PrettyFormatOptions;
reporters: Array<string | ReporterConfig>;
logHeapUsage: boolean;
lastCommit: boolean;
Expand Down Expand Up @@ -217,6 +218,7 @@ export type InitialOptions = Partial<{
slowTestThreshold: number;
snapshotResolver: Path;
snapshotSerializers: Array<Path>;
snapshotFormat: PrettyFormatOptions;
errorOnDeprecated: boolean;
testEnvironment: string;
testEnvironmentOptions: Record<string, unknown>;
Expand Down Expand Up @@ -293,7 +295,7 @@ export type GlobalConfig = {
json: boolean;
globalSetup?: string;
globalTeardown?: string;
inlineSnapshotFormatter: 'exposed prototypes' | 'simple';
inlineSnapshotFormat: PrettyFormatOptions;
lastCommit: boolean;
logHeapUsage: boolean;
listTests: boolean;
Expand All @@ -315,6 +317,7 @@ export type GlobalConfig = {
rootDir: Path;
silent?: boolean;
skipFilter: boolean;
snapshotFormat: PrettyFormatOptions;
errorOnDeprecated: boolean;
testFailureExitCode: number;
testNamePattern?: string;
Expand Down Expand Up @@ -354,7 +357,7 @@ export type ProjectConfig = {
globalTeardown?: string;
globals: ConfigGlobals;
haste: HasteConfig;
inlineSnapshotFormatter: 'exposed prototypes' | 'simple';
inlineSnapshotFormat: PrettyFormatOptions;
injectGlobals: boolean;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
Expand All @@ -378,6 +381,7 @@ export type ProjectConfig = {
slowTestThreshold: number;
snapshotResolver?: Path;
snapshotSerializers: Array<Path>;
snapshotFormat: PrettyFormatOptions;
testEnvironment: string;
testEnvironmentOptions: Record<string, unknown>;
testMatch: Array<Glob>;
Expand Down
2 changes: 1 addition & 1 deletion packages/pretty-format/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME) as Array<
keyof typeof DEFAULT_THEME
>;

const DEFAULT_OPTIONS: Options = {
export const DEFAULT_OPTIONS: Options = {
callToJSON: true,
escapeRegex: false,
escapeString: true,
Expand Down
6 changes: 4 additions & 2 deletions packages/test-utils/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const DEFAULT_GLOBAL_CONFIG: Config.GlobalConfig = {
forceExit: false,
globalSetup: undefined,
globalTeardown: undefined,
inlineSnapshotFormatter: 'exposed prototypes',
inlineSnapshotFormat: {},
json: false,
lastCommit: false,
listTests: false,
Expand All @@ -50,6 +50,7 @@ const DEFAULT_GLOBAL_CONFIG: Config.GlobalConfig = {
runTestsByPath: false,
silent: false,
skipFilter: false,
snapshotFormat: {},
testFailureExitCode: 1,
testNamePattern: '',
testPathPattern: '',
Expand Down Expand Up @@ -85,7 +86,7 @@ const DEFAULT_PROJECT_CONFIG: Config.ProjectConfig = {
globals: {},
haste: {},
injectGlobals: true,
inlineSnapshotFormatter: 'exposed prototypes',
inlineSnapshotFormat: {},
moduleDirectories: [],
moduleFileExtensions: ['js'],
moduleLoader: '/test_module_loader_path',
Expand All @@ -106,6 +107,7 @@ const DEFAULT_PROJECT_CONFIG: Config.ProjectConfig = {
skipFilter: false,
skipNodeResolution: false,
slowTestThreshold: 5,
snapshotFormat: {},
snapshotResolver: undefined,
snapshotSerializers: [],
testEnvironment: 'node',
Expand Down

0 comments on commit f8e6d51

Please sign in to comment.