Skip to content

Commit

Permalink
Prevent drifting inline snapshots jestjs#8424
Browse files Browse the repository at this point in the history
Fixes jestjs#8424 by avoiding indenting inline snapshot if second
line of inline snapshot already has been indented.
  • Loading branch information
petternordholm committed May 23, 2019
1 parent c24934c commit 3ecaf66
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
31 changes: 31 additions & 0 deletions packages/jest-snapshot/src/__tests__/inline_snapshots.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,37 @@ test('saveInlineSnapshots() indents multi-line snapshots with spaces', () => {
);
});

test('saveInlineSnapshots() does not re-indent already indented snapshots', () => {
const filename = path.join(__dirname, 'my.test.js');
(fs.readFileSync as jest.Mock).mockImplementation(
() =>
"it('is a test', () => {\n" +
" expect({a: 'a'}).toMatchInlineSnapshot(`\n" +
' Object {\n' +
" a: 'a'\n" +
' }\n' +
' `);\n' +
'});\n',
);
(prettier.resolveConfig.sync as jest.Mock).mockReturnValue({
bracketSpacing: false,
singleQuote: true,
});

saveInlineSnapshots(
[
{
frame: {column: 20, file: filename, line: 2} as Frame,
snapshot: `\n Object {\n a: 'a'\n }\n`,
},
],
prettier,
babelTraverse,
);

expect(fs.writeFileSync).not.toHaveBeenCalled();
});

test('saveInlineSnapshots() indents multi-line snapshots with tabs', () => {
const filename = path.join(__dirname, 'my.test.js');
(fs.readFileSync as jest.Mock).mockImplementation(
Expand Down
5 changes: 4 additions & 1 deletion packages/jest-snapshot/src/inline_snapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,14 +120,17 @@ const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file);

const indent = (snapshot: string, numIndents: number, indentation: string) => {
const lines = snapshot.split('\n');
const secondAlreadyLineIndented =

This comment has been minimized.

Copy link
@olandersson

olandersson May 24, 2019

secondLineAlreadyIndented

lines.length > 2 && lines[1].startsWith(indentation.repeat(numIndents + 1));

return lines
.map((line, index) => {
if (index === 0) {
// First line is either a 1-line snapshot or a blank line.
return line;
} else if (index !== lines.length - 1) {
// Do not indent empty lines.

This comment has been minimized.

Copy link
@olandersson

olandersson May 24, 2019

// Do not indent empty, or already indented, lines.

if (line === '') {
if (line === '' || secondAlreadyLineIndented) {
return line;
}

Expand Down

0 comments on commit 3ecaf66

Please sign in to comment.