Skip to content

Commit 7c872ee

Browse files
thymikeecpojer
authored andcommitted
Unescape serialized snapshots for diffing (jestjs#2852)
* Unescape serialized snapshots for diffing * Normalize \r same way as \r\n by @rubenmoya * Don't unescape regex for now
1 parent c6be35f commit 7c872ee

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

packages/jest-snapshot/src/State.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const {
1919
keyToTestName,
2020
serialize,
2121
testNameToKey,
22+
unescape,
2223
} = require('./utils');
2324
const fileExists = require('jest-file-exists');
2425
const fs = require('fs');
@@ -158,9 +159,9 @@ class SnapshotState {
158159
if (!pass) {
159160
this.unmatched++;
160161
return {
161-
actual: receivedSerialized,
162+
actual: unescape(receivedSerialized),
162163
count,
163-
expected,
164+
expected: unescape(expected),
164165
pass: false,
165166
};
166167
} else {

packages/jest-snapshot/src/__tests__/utils-test.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ test('getSnapshotPath()', () => {
4141
);
4242
});
4343

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

55+
test('saveSnapshotFile() works with \r', () => {
56+
const filename = path.join(__dirname, 'remove-newlines.snap');
57+
const data = {
58+
myKey: '<div>\r</div>',
59+
};
60+
61+
saveSnapshotFile(data, filename);
62+
expect(fs.writeFileSync)
63+
.toBeCalledWith(filename, 'exports[`myKey`] = `<div>\n</div>`;\n');
64+
});
65+
5566
test('escaping', () => {
5667
const filename = path.join(__dirname, 'escaping.snap');
5768
const data = '"\'\\';

packages/jest-snapshot/src/utils.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@ const serialize = (data: any): string => {
6666
}));
6767
};
6868

69+
const unescape = (data: any): string =>
70+
data.replace(/\\(")/g, '$1'); // unescape double quotes
71+
6972
const printBacktickString = (str: string) => {
7073
return '`' + str.replace(/`|\\|\${/g, '\\$&') + '`';
7174
};
@@ -77,7 +80,7 @@ const ensureDirectoryExists = (filePath: Path) => {
7780
};
7881

7982
const normalizeNewlines =
80-
string => string.replace(/\r\n/g, '\n');
83+
string => string.replace(/\r\n|\r/g, '\n');
8184

8285
const saveSnapshotFile = (
8386
snapshotData: {[key: string]: string},
@@ -102,4 +105,5 @@ module.exports = {
102105
saveSnapshotFile,
103106
serialize,
104107
testNameToKey,
108+
unescape,
105109
};

0 commit comments

Comments
 (0)