Skip to content

Commit

Permalink
Prevent drifting inline snapshots #8424
Browse files Browse the repository at this point in the history
Fixes #8424 by avoiding indenting inline snapshot if second
line of inline snapshot already has been indented.
  • Loading branch information
petternordholm committed May 24, 2019
1 parent c24934c commit 3f9ca85
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
50 changes: 50 additions & 0 deletions packages/jest-snapshot/src/__tests__/inline_snapshots.test.ts
Expand Up @@ -236,6 +236,56 @@ 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" +
'});\n' +
"it('is a another test', () => {\n" +
" expect({a: 'a'}).toMatchInlineSnapshot(`\n" +
' Object {\n' +
" b: 'b'\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: `\nObject {\n a: 'a'\n}\n`,
},
],
prettier,
babelTraverse,
);

expect(fs.writeFileSync).toHaveBeenCalledWith(
filename,
"it('is a test', () => {\n" +
" expect({a: 'a'}).toMatchInlineSnapshot(`\n" +
' Object {\n' +
" a: 'a'\n" +
' }\n' +
' `);\n' +
'});\n' +
"it('is a another test', () => {\n" +
" expect({a: 'a'}).toMatchInlineSnapshot(`\n" +
' Object {\n' +
" b: 'b'\n" +
' }\n' +
' `);\n' +
'});\n',
);
});

test('saveInlineSnapshots() indents multi-line snapshots with tabs', () => {
const filename = path.join(__dirname, 'my.test.js');
(fs.readFileSync as jest.Mock).mockImplementation(
Expand Down
7 changes: 7 additions & 0 deletions packages/jest-snapshot/src/inline_snapshots.ts
Expand Up @@ -120,6 +120,13 @@ const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file);

const indent = (snapshot: string, numIndents: number, indentation: string) => {
const lines = snapshot.split('\n');
if (
lines.length > 2 &&
lines[1].startsWith(indentation.repeat(numIndents + 1))
) {
return snapshot;
}

return lines
.map((line, index) => {
if (index === 0) {
Expand Down

0 comments on commit 3f9ca85

Please sign in to comment.