1
import * as fs from "fs";
2
import * as path from "path";
3
import * as chalk from "chalk";
4
import { matcherHint, printDiffOrStringify } from "jest-matcher-utils";
6
import { diffSVGToSnapshot } from "./diffSVGToSnapshot";
8
const SNAPSHOTS_DIR = "__snapshots__";
10
function updateSnapshotState(
11
originalSnapshotState: any,
12
partialSnapshotState: any
14
if (global.UNSTABLE_SKIP_REPORTING) {
15
return originalSnapshotState;
17
return { ...originalSnapshotState, ...partialSnapshotState };
20
function createSnapshotIdentifier({
26
currentTestName: string;
29
const counter = snapshotState._counters.get(currentTestName);
30
const snapshotIdentifier = `${path.basename(
32
)}-${currentTestName}-${counter}`
37
return snapshotIdentifier;
40
export default function toMatchSVGSnapshot(received: string) {
41
// getState isn't in the d.ts for Jest, this is ok though.
42
const { testPath, currentTestName, isNot, snapshotState, expand } =
45
currentTestName: string;
53
"Jest: `.not` cannot be used with `.toMatchSVGSnapshot()`."
57
updateSnapshotState(snapshotState, {
58
_counters: snapshotState._counters.set(
60
(snapshotState._counters.get(currentTestName) || 0) + 1
64
const snapshotIdentifier = createSnapshotIdentifier({
70
// Figure out the paths
71
const snapshotsDir = path.join(path.dirname(testPath), SNAPSHOTS_DIR);
72
const expectedSnapshot = path.join(
74
`${snapshotIdentifier}-snap.svg`
78
snapshotState._updateSnapshot === "none" &&
79
!fs.existsSync(expectedSnapshot)
84
`New snapshot was ${chalk.bold.red(
86
)}. The update flag must be explicitly ` +
87
"passed to write a new snapshot.\n\n + This is likely because this test is run in a continuous " +
88
"integration (CI) environment in which snapshots are not written by default.\n\n",
92
const result = diffSVGToSnapshot({
93
receivedSVG: received,
96
updateSnapshot: snapshotState._updateSnapshot === "all",
101
let message = () => "";
103
if (result.updated) {
104
// once transition away from jasmine is done this will be a lot more elegant and pure
105
// https://github.com/facebook/jest/pull/3668
106
updateSnapshotState(snapshotState, {
107
updated: snapshotState.updated + 1,
109
} else if (result.added) {
110
updateSnapshotState(snapshotState, { added: snapshotState.added + 1 });
114
updateSnapshotState(snapshotState, {
115
matched: snapshotState.matched + 1,
119
updateSnapshotState(snapshotState, {
120
unmatched: snapshotState.unmatched + 1,
125
matcherHint(".toMatchSVGSnapshot", "received", "") +
127
"Expected SVGs to match:\n" +
128
` ${printDiffOrStringify(