Skip to content

Instantly share code, notes, and snippets.

@bdombro
Last active March 10, 2022 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdombro/762d557a94d4146564e347db8fc1985a to your computer and use it in GitHub Desktop.
Save bdombro/762d557a94d4146564e347db8fc1985a to your computer and use it in GitHub Desktop.
jest-update-snaps.mjs
#!/usr/bin/env zx
/* eslint-disable i18next/no-literal-string */
// eslint-disable-next-line import/no-unresolved
import { startSpinner } from 'zx/experimental';
import {
assertGit,
assertGithubCli,
getGitCtx,
HandledError,
log,
throwError,
} from './zx-lib.mjs';
/**
* update-snaps.mjs
* - Update all test snapshots without running other tests. Is 200%+
* faster than running \`yarn jest:quiet -u\`
*/
export default async function main({
commit,
push,
pushf,
amend,
maxWorkers = '80%',
}) {
await log.announce('UPDATING SNAPSHOTS');
await assertGit();
if (push || pushf) {
await assertGithubCli();
}
try {
let ctx = await getGitCtx();
const snaps = (await $`find src -name "*.snap"`).stdout
.split('\n')
.filter(s => s.trim());
const tests = snaps.map(s =>
s.replace('__snapshots__/', '').replace('.snap', ''),
);
await log('running jest...');
const stopSpinner = startSpinner();
await $`yarn jest:quiet -u --silent --maxWorkers=${maxWorkers} ${tests}`;
stopSpinner();
const updates = (await $`git status --porcelain`).stdout
.split('\n')
.filter(s => s.trim())
.filter(s => s.includes('.snap'))
.map(s => s.replace(/^ [A-Z] /, '')); // removes ' M '
if (updates.length) {
await log.info(`found ${updates.length} updates`);
if (amend || commit || push || pushf) {
await log.info('committing');
ctx = await getCtx();
if (ctx.branch === 'master')
throwError('dont commit on master branch!');
await $`git add ${snaps}`;
if (amend) await $`git commit --no-edit --no-verify --amend`;
else await $`git commit -m "Update snaps" --no-verify`;
}
if (pushf) {
await log.info('force pushing');
ctx = await getCtx();
if (ctx.branch === 'master') throwError('dont push to master branch!');
await $`git push -f`;
} else if (push) {
await log.info('pushing');
ctx = await getCtx();
if (ctx.branch === 'master') throwError('dont push to master branch!');
await $`git push -u origin HEAD`;
}
} else {
await log.info('snaps were already up to date');
}
await log.say('update snaps done');
await log.announce('DONE');
} catch (e) {
await log.say('error snapshots failed');
if (e instanceof HandledError) await log.error(e.message);
else throw e;
}
}
const isCalled =
process.argv[2].split('/').pop() === import.meta.url.split('/').pop();
if (isCalled) {
$.verbose = argv.verbose;
$.silent = argv.silent;
if (!globalThis.$) {
throwError(
'This script must be ran using zx (https://github.com/google/zx)',
);
}
main(argv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment