RepliCAD

Форк
0
/
toMatchSVGSnapshot.ts 
144 строки · 3.5 Кб
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";
5

6
import { diffSVGToSnapshot } from "./diffSVGToSnapshot";
7

8
const SNAPSHOTS_DIR = "__snapshots__";
9

10
function updateSnapshotState(
11
  originalSnapshotState: any,
12
  partialSnapshotState: any
13
) {
14
  if (global.UNSTABLE_SKIP_REPORTING) {
15
    return originalSnapshotState;
16
  }
17
  return { ...originalSnapshotState, ...partialSnapshotState };
18
}
19

20
function createSnapshotIdentifier({
21
  testPath,
22
  currentTestName,
23
  snapshotState,
24
}: {
25
  testPath: string;
26
  currentTestName: string;
27
  snapshotState: any;
28
}) {
29
  const counter = snapshotState._counters.get(currentTestName);
30
  const snapshotIdentifier = `${path.basename(
31
    testPath
32
  )}-${currentTestName}-${counter}`
33
    .replace(/\s+/g, "-")
34
    .replace(/\//g, "-")
35
    .toLowerCase();
36

37
  return snapshotIdentifier;
38
}
39

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 } =
43
    this as any as {
44
      testPath: string;
45
      currentTestName: string;
46
      isNot: boolean;
47
      snapshotState: any;
48
      expand: boolean;
49
    };
50

51
  if (isNot) {
52
    throw new Error(
53
      "Jest: `.not` cannot be used with `.toMatchSVGSnapshot()`."
54
    );
55
  }
56

57
  updateSnapshotState(snapshotState, {
58
    _counters: snapshotState._counters.set(
59
      currentTestName,
60
      (snapshotState._counters.get(currentTestName) || 0) + 1
61
    ),
62
  });
63

64
  const snapshotIdentifier = createSnapshotIdentifier({
65
    testPath,
66
    currentTestName,
67
    snapshotState,
68
  });
69

70
  //  Figure out the paths
71
  const snapshotsDir = path.join(path.dirname(testPath), SNAPSHOTS_DIR);
72
  const expectedSnapshot = path.join(
73
    snapshotsDir,
74
    `${snapshotIdentifier}-snap.svg`
75
  );
76

77
  if (
78
    snapshotState._updateSnapshot === "none" &&
79
    !fs.existsSync(expectedSnapshot)
80
  ) {
81
    return {
82
      pass: false,
83
      message: () =>
84
        `New snapshot was ${chalk.bold.red(
85
          "not written"
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",
89
    };
90
  }
91

92
  const result = diffSVGToSnapshot({
93
    receivedSVG: received,
94
    snapshotIdentifier,
95
    snapshotsDir,
96
    updateSnapshot: snapshotState._updateSnapshot === "all",
97
  });
98

99
  let pass = true;
100

101
  let message = () => "";
102

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,
108
    });
109
  } else if (result.added) {
110
    updateSnapshotState(snapshotState, { added: snapshotState.added + 1 });
111
  } else {
112
    ({ pass } = result);
113

114
    updateSnapshotState(snapshotState, {
115
      matched: snapshotState.matched + 1,
116
    });
117

118
    if (!pass) {
119
      updateSnapshotState(snapshotState, {
120
        unmatched: snapshotState.unmatched + 1,
121
      });
122

123
      message = () => {
124
        return (
125
          matcherHint(".toMatchSVGSnapshot", "received", "") +
126
          "\n\n" +
127
          "Expected SVGs to match:\n" +
128
          `  ${printDiffOrStringify(
129
            result.expected,
130
            received,
131
            "Expected",
132
            "Received",
133
            expand !== false
134
          )}`
135
        );
136
      };
137
    }
138
  }
139

140
  return {
141
    message,
142
    pass,
143
  };
144
}
145

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.