-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
RFC: Format snapshot changes ourselves (#1222)
This misappropriates Jest's reporter functionality so we can plug in to test file execution and re-format files that have updated snapshots. Alternative to #1220.
- Loading branch information
Showing
4 changed files
with
62 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import type { Reporter } from '@jest/reporters'; | ||
import fs from 'fs-extra'; | ||
import { resolveConfig } from 'prettier'; | ||
|
||
import { formatOrLintFile } from '../../../../cli/adapter/prettier'; | ||
|
||
export default class SnapshotPrettifier | ||
implements Pick<Reporter, 'onTestFileResult'> | ||
{ | ||
async onTestFileResult( | ||
...[test, testResult]: Parameters<NonNullable<Reporter['onTestFileResult']>> | ||
): Promise<void> { | ||
if (!testResult.snapshot.added && !testResult.snapshot.updated) { | ||
return; | ||
} | ||
|
||
const filepath = test.path; | ||
|
||
// This is a best-effort workaround to automatically format code. | ||
// Don't pollute console output if it fails for whatever reason. | ||
try { | ||
const [config, data] = await Promise.all([ | ||
resolveConfig(filepath), | ||
fs.promises.readFile(filepath, 'utf-8'), | ||
]); | ||
|
||
const formatted = await formatOrLintFile( | ||
{ | ||
data, | ||
filepath, | ||
options: { | ||
...config, | ||
filepath, | ||
}, | ||
}, | ||
'format', | ||
null, | ||
); | ||
|
||
if (typeof formatted === 'string') { | ||
await fs.promises.writeFile(filepath, formatted); | ||
} | ||
} catch {} | ||
} | ||
} |