MCPcopy
hub / github.com/jestjs/jest / stripAddedIndentation

Function stripAddedIndentation

packages/jest-snapshot/src/index.ts:72–112  ·  view source on GitHub ↗
(inlineSnapshot: string)

Source from the content-addressed store, hash-verified

70};
71
72function stripAddedIndentation(inlineSnapshot: string) {
73 // Find indentation if exists.
74 const match = inlineSnapshot.match(INDENTATION_REGEX);
75 if (!match || !match[1]) {
76 // No indentation.
77 return inlineSnapshot;
78 }
79
80 const indentation = match[1];
81 const lines = inlineSnapshot.split('\n');
82 if (lines.length <= 2) {
83 // Must be at least 3 lines.
84 return inlineSnapshot;
85 }
86
87 if (lines[0].trim() !== '' || lines.at(-1)!.trim() !== '') {
88 // If not blank first and last lines, abort.
89 return inlineSnapshot;
90 }
91
92 for (let i = 1; i < lines.length - 1; i++) {
93 if (lines[i] !== '') {
94 if (lines[i].indexOf(indentation) !== 0) {
95 // All lines except first and last should either be blank or have the same
96 // indent as the first line (or more). If this isn't the case we don't
97 // want to touch the snapshot at all.
98 return inlineSnapshot;
99 }
100
101 lines[i] = lines[i].slice(indentation.length);
102 }
103 }
104
105 // Last line is a special case because it won't have the same indent as others
106 // but may still have been given some indent to line up.
107 lines[lines.length - 1] = '';
108
109 // Return inline snapshot, now at indent 0.
110 inlineSnapshot = lines.join('\n');
111 return inlineSnapshot;
112}
113
114const fileExists = (filePath: string, fileSystem: FileSystem): boolean =>
115 fileSystem.exists(filePath) || fs.existsSync(filePath);

Callers 2

toMatchInlineSnapshotFunction · 0.85

Calls 1

matchMethod · 0.80

Tested by

no test coverage detected