@@ -8,14 +8,18 @@ const assert = require('node:assert/strict');
8
8
const stackFramesRegexp = / ( \s + ) ( ( .+ ?) \s + \( ) ? (?: \( ? ( .+ ?) : ( \d + ) (?: : ( \d + ) ) ? ) \) ? ( \s + \{ ) ? ( \n | $ ) / g;
9
9
const windowNewlineRegexp = / \r / g;
10
10
11
- function replaceStackTrace ( str ) {
12
- return str . replace ( stackFramesRegexp , '$1*$7\n' ) ;
11
+ function replaceStackTrace ( str , replacement = '$1*$7\n' ) {
12
+ return str . replace ( stackFramesRegexp , replacement ) ;
13
13
}
14
14
15
15
function replaceWindowsLineEndings ( str ) {
16
16
return str . replace ( windowNewlineRegexp , '' ) ;
17
17
}
18
18
19
+ function replaceWindowsPaths ( str ) {
20
+ return str . replaceAll ( path . win32 . sep , path . posix . sep ) ;
21
+ }
22
+
19
23
function transform ( ...args ) {
20
24
return ( str ) => args . reduce ( ( acc , fn ) => fn ( acc ) , str ) ;
21
25
}
@@ -35,19 +39,32 @@ async function assertSnapshot(actual, filename = process.argv[1]) {
35
39
}
36
40
}
37
41
42
+ /**
43
+ * Spawn a process and assert its output against a snapshot.
44
+ * if you want to automatically update the snapshot, run tests with NODE_REGENERATE_SNAPSHOTS=1
45
+ * transform is a function that takes the output and returns a string that will be compared against the snapshot
46
+ * this is useful for normalizing output such as stack traces
47
+ * there are some predefined transforms in this file such as replaceStackTrace and replaceWindowsLineEndings
48
+ * both of which can be used as an example for writing your own
49
+ * compose multiple transforms by passing them as arguments to the transform function:
50
+ * assertSnapshot.transform(assertSnapshot.replaceStackTrace, assertSnapshot.replaceWindowsLineEndings)
51
+ *
52
+ * @param {string } filename
53
+ * @param {function(string): string } [transform]
54
+ * @returns {Promise<void> }
55
+ */
38
56
async function spawnAndAssert ( filename , transform = ( x ) => x ) {
39
- // TODO: Add an option to this function to alternatively or additionally compare stderr.
40
- // For now, tests that want to check stderr or both stdout and stderr can use spawnPromisified.
41
57
const flags = common . parseTestFlags ( filename ) ;
42
- const { stdout } = await common . spawnPromisified ( process . execPath , [ ...flags , filename ] ) ;
43
- await assertSnapshot ( transform ( stdout ) , filename ) ;
58
+ const { stdout, stderr } = await common . spawnPromisified ( process . execPath , [ ...flags , filename ] ) ;
59
+ await assertSnapshot ( transform ( ` ${ stdout } ${ stderr } ` ) , filename ) ;
44
60
}
45
61
46
62
module . exports = {
47
63
assertSnapshot,
48
64
getSnapshotPath,
49
65
replaceStackTrace,
50
66
replaceWindowsLineEndings,
67
+ replaceWindowsPaths,
51
68
spawnAndAssert,
52
69
transform,
53
70
} ;
0 commit comments