Skip to content

Commit

Permalink
Snapshot testing for the articles transformer
Browse files Browse the repository at this point in the history
  • Loading branch information
jamieparkinson committed Apr 27, 2023
1 parent 0bfcef7 commit 4da245b
Show file tree
Hide file tree
Showing 11 changed files with 3,047 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pipeline/test/prismic-snapshots/*.json linguist-generated=true
*.shot linguist-language=Jest-Snapshot
*.shot linguist-generated
1 change: 1 addition & 0 deletions pipeline/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"scripts": {
"package": "./package.sh",
"reindex": "ts-node src/local.ts",
"update-prismic-snapshots": "ts-node test/update-prismic-snapshots.ts",
"test": "jest"
},
"dependencies": {
Expand Down
40 changes: 40 additions & 0 deletions pipeline/test/fixtures/forEachPrismicSnapshot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import fs from "node:fs";
import path from "node:path";
import { test } from "@jest/globals";
import type { Global as JestGlobal } from "@jest/types";
import { ContentType } from "../../src/types";
import { PrismicDocument } from "@prismicio/types";

// Hold snapshots in memory rather than reading from the filesystem for every test
const snapshotCache = new Map<string, any>();
const contentTypesCache = new Map<ContentType, string[]>();

const dataDir = path.resolve(__dirname, "../prismic-snapshots");

const getSnapshot = <T>(name: string): T => {
if (snapshotCache.has(name)) {
return snapshotCache.get(name);
}
return JSON.parse(
fs.readFileSync(path.resolve(dataDir, name), { encoding: "utf-8" })
);
};

const snapshotNamesForContentType = (contentType: ContentType): string[] =>
contentTypesCache.get(contentType) ??
fs.readdirSync(dataDir).filter((f) => f.endsWith(`${contentType}.json`));

const forEachPrismicSnapshot = <T extends PrismicDocument>(
...contentTypes: ContentType[]
) => {
const snapshots = contentTypes
.flatMap(snapshotNamesForContentType)
.map(getSnapshot<T>);

return <EachFn extends JestGlobal.TestFn | JestGlobal.BlockFn>(
description: string,
testCase: (snapshot: T) => ReturnType<EachFn>
) => test.each(snapshots)(`${description} (document: $type/$id)`, testCase);
};

export default forEachPrismicSnapshot;
Loading

0 comments on commit 4da245b

Please sign in to comment.