Skip to content

Commit

Permalink
Unescape serialized snapshots for diffing (jestjs#2852)
Browse files Browse the repository at this point in the history
* Unescape serialized snapshots for diffing

* Normalize \r same way as \r\n by @rubenmoya

* Don't unescape regex for now
  • Loading branch information
thymikee authored and cpojer committed Feb 10, 2017
1 parent c6be35f commit 7c872ee
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 3 additions & 2 deletions packages/jest-snapshot/src/State.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const {
keyToTestName,
serialize,
testNameToKey,
unescape,
} = require('./utils');
const fileExists = require('jest-file-exists');
const fs = require('fs');
Expand Down Expand Up @@ -158,9 +159,9 @@ class SnapshotState {
if (!pass) {
this.unmatched++;
return {
actual: receivedSerialized,
actual: unescape(receivedSerialized),
count,
expected,
expected: unescape(expected),
pass: false,
};
} else {
Expand Down
13 changes: 12 additions & 1 deletion packages/jest-snapshot/src/__tests__/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ test('getSnapshotPath()', () => {
);
});

test('saveSnapshotFile()', () => {
test('saveSnapshotFile() works with \r\n', () => {
const filename = path.join(__dirname, 'remove-newlines.snap');
const data = {
myKey: '<div>\r\n</div>',
Expand All @@ -52,6 +52,17 @@ test('saveSnapshotFile()', () => {
.toBeCalledWith(filename, 'exports[`myKey`] = `<div>\n</div>`;\n');
});

test('saveSnapshotFile() works with \r', () => {
const filename = path.join(__dirname, 'remove-newlines.snap');
const data = {
myKey: '<div>\r</div>',
};

saveSnapshotFile(data, filename);
expect(fs.writeFileSync)
.toBeCalledWith(filename, 'exports[`myKey`] = `<div>\n</div>`;\n');
});

test('escaping', () => {
const filename = path.join(__dirname, 'escaping.snap');
const data = '"\'\\';
Expand Down
6 changes: 5 additions & 1 deletion packages/jest-snapshot/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ const serialize = (data: any): string => {
}));
};

const unescape = (data: any): string =>
data.replace(/\\(")/g, '$1'); // unescape double quotes

const printBacktickString = (str: string) => {
return '`' + str.replace(/`|\\|\${/g, '\\$&') + '`';
};
Expand All @@ -77,7 +80,7 @@ const ensureDirectoryExists = (filePath: Path) => {
};

const normalizeNewlines =
string => string.replace(/\r\n/g, '\n');
string => string.replace(/\r\n|\r/g, '\n');

const saveSnapshotFile = (
snapshotData: {[key: string]: string},
Expand All @@ -102,4 +105,5 @@ module.exports = {
saveSnapshotFile,
serialize,
testNameToKey,
unescape,
};

0 comments on commit 7c872ee

Please sign in to comment.