Skip to content

Commit cb35442

Browse files
committed
fix: Support diffing single-line strings
1 parent 13001eb commit cb35442

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

__tests__/__snapshots__/snapshotDiff.test.js.snap

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,13 @@ exports[`failed optional deps throws with sensible message on missing react-test
134134
"Failed to load optional module \\"react-test-renderer\\". If you need to compare React elements, please add \\"react-test-renderer\\" to your project's dependencies.
135135
Cannot find module 'non-existent-module-for-testing' from 'snapshotDiff.test.js'"
136136
`;
137+
138+
exports[`supports diffing single-line strings 1`] = `
139+
"Snapshot Diff:
140+
- First value
141+
+ Second value
142+
143+
- foo
144+
+ bar
145+
"
146+
`;

__tests__/snapshotDiff.test.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ class Component extends React.Component<Props> {
5656
}
5757
}
5858

59+
test('supports diffing single-line strings', () => {
60+
expect(snapshotDiff('foo', 'bar')).toMatchSnapshot();
61+
});
62+
5963
test('collapses diffs and strips ansi by default', () => {
6064
expect(snapshotDiff(a, b)).toMatchSnapshot();
6165
});

src/index.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const prettyFormat = require('pretty-format');
88

99
const { ReactElement } = prettyFormat.plugins;
1010
const reactElement = Symbol.for('react.element');
11+
const MULTILINE_REGEXP = /[\r\n]/;
1112

1213
type Options = {
1314
expand?: boolean,
@@ -50,6 +51,15 @@ const isReactComponent = (value: any) =>
5051
value && value.$$typeof === reactElement;
5152

5253
function diffStrings(valueA: any, valueB: any, options: Options) {
54+
const multiline =
55+
MULTILINE_REGEXP.test(valueA) && MULTILINE_REGEXP.test(valueB);
56+
57+
// jest-diff doesn't support single-line values, but we want to
58+
if (typeof valueA === 'string' && typeof valueB === 'string' && !multiline) {
59+
valueA += '\n'; // eslint-disable-line no-param-reassign
60+
valueB += '\n'; // eslint-disable-line no-param-reassign
61+
}
62+
5363
return diff(valueA, valueB, {
5464
expand: options.expand,
5565
contextLines: options.contextLines,

0 commit comments

Comments
 (0)