Storyshots integrity: remove abandoned storyshots when running with -u flag

This commit is contained in:
Filipp Riabchun 2019-11-19 23:47:31 +01:00
parent 2cf7f375dd
commit 723ad13416

View File

@ -2,6 +2,52 @@
import fs from 'fs';
import glob from 'glob';
import { describe, it } from 'global';
import dedent from 'ts-dedent';
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace,no-redeclare
namespace jest {
interface Matchers<R, T> {
notToBeAbandoned(stories2snapsConverter: any): R;
}
}
}
expect.extend({
notToBeAbandoned(storyshots, stories2snapsConverter) {
const abandonedStoryshots = storyshots.filter((fileName: string) => {
const possibleStoriesFiles = stories2snapsConverter.getPossibleStoriesFiles(fileName);
return !possibleStoriesFiles.some(fs.existsSync);
});
if (abandonedStoryshots.length === 0) {
return { pass: true, message: () => '' };
}
const formattedList = abandonedStoryshots.join('\n ');
// See https://github.com/facebook/jest/issues/8732#issuecomment-516445064
// eslint-disable-next-line no-underscore-dangle
const isUpdate = expect.getState().snapshotState._updateSnapshot === 'all';
if (isUpdate) {
abandonedStoryshots.forEach((file: string) => fs.unlinkSync(file));
// eslint-disable-next-line no-console
console.log(dedent`
Removed abandoned storyshots:
${formattedList}
`);
return { pass: true, message: () => '' };
}
return {
pass: false,
message: () => dedent`
Found abandoned storyshots. Run jest with -u to remove them:
${formattedList}
`,
};
},
});
function integrityTest(integrityOptions: any, stories2snapsConverter: any) {
if (integrityOptions === false) {
@ -13,12 +59,7 @@ function integrityTest(integrityOptions: any, stories2snapsConverter: any) {
const snapshotExtension = stories2snapsConverter.getSnapshotExtension();
const storyshots = glob.sync(`**/*${snapshotExtension}`, integrityOptions);
const abandonedStoryshots = storyshots.filter(fileName => {
const possibleStoriesFiles = stories2snapsConverter.getPossibleStoriesFiles(fileName);
return !possibleStoriesFiles.some(fs.existsSync);
});
expect(abandonedStoryshots).toEqual([]);
expect(storyshots).notToBeAbandoned(stories2snapsConverter);
});
});
}