Skip to content

Commit a8334ce

Browse files
thymikeecpojer
authored andcommitted
Highlight trailing whitespace inside snapshots (jestjs#2347)
1 parent be81c84 commit a8334ce

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

packages/jest-diff/src/diffStrings.js

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,19 @@ export type DiffOptions = {|
2424

2525
type Diff = {diff: string, isDifferent: boolean};
2626

27+
const getColor = (added: boolean, removed: boolean): chalk =>
28+
added
29+
? chalk.red
30+
: (removed ? chalk.green : chalk.dim);
31+
32+
const getBgColor = (added: boolean, removed: boolean): chalk =>
33+
added
34+
? chalk.bgRed
35+
: (removed ? chalk.bgGreen : chalk.dim);
36+
37+
const highlightTrailingWhitespace = (line: string, bgColor: Function): string =>
38+
line.replace(/\s+$/, bgColor('$&'));
39+
2740
const getAnnotation = (options: ?DiffOptions): string =>
2841
chalk.green('- ' + ((options && options.aAnnotation) || 'Expected')) + '\n' +
2942
chalk.red('+ ' + ((options && options.bAnnotation) || 'Received')) + '\n\n';
@@ -32,22 +45,23 @@ const diffLines = (a: string, b: string): Diff => {
3245
let isDifferent = false;
3346
return {
3447
diff: diff.diffLines(a, b).map(part => {
48+
const {added, removed} = part;
3549
if (part.added || part.removed) {
3650
isDifferent = true;
3751
}
3852

3953
const lines = part.value.split('\n');
40-
const color = part.added
41-
? chalk.red
42-
: (part.removed ? chalk.green : chalk.dim);
54+
const color = getColor(added, removed);
55+
const bgColor = getBgColor(added, removed);
4356

4457
if (lines[lines.length - 1] === '') {
4558
lines.pop();
4659
}
4760

4861
return lines.map(line => {
62+
const highlightedLine = highlightTrailingWhitespace(line, bgColor);
4963
const mark = color(part.added ? '+' : part.removed ? '-' : ' ');
50-
return mark + ' ' + color(line) + '\n';
64+
return mark + ' ' + color(highlightedLine) + '\n';
5165
}).join('');
5266
}).join('').trim(),
5367
isDifferent,
@@ -76,11 +90,11 @@ const structuredPatch = (a: string, b: string): Diff => {
7690
const added = line[0] === '+';
7791
const removed = line[0] === '-';
7892

79-
const color = added
80-
? chalk.red
81-
: (removed ? chalk.green : chalk.dim);
93+
const color = getColor(added, removed);
94+
const bgColor = getBgColor(added, removed);
8295

83-
return color(line) + '\n';
96+
const highlightedLine = highlightTrailingWhitespace(line, bgColor);
97+
return color(highlightedLine) + '\n';
8498
}).join('');
8599

86100
isDifferent = true;

0 commit comments

Comments
 (0)