index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. 'use strict';
  2. var fs = _interopRequireWildcard(require('graceful-fs'));
  3. var _jestMatcherUtils = require('jest-matcher-utils');
  4. var _SnapshotResolver = require('./SnapshotResolver');
  5. var _State = _interopRequireDefault(require('./State'));
  6. var _plugins = require('./plugins');
  7. var _printSnapshot = require('./printSnapshot');
  8. var utils = _interopRequireWildcard(require('./utils'));
  9. function _interopRequireDefault(obj) {
  10. return obj && obj.__esModule ? obj : {default: obj};
  11. }
  12. function _getRequireWildcardCache(nodeInterop) {
  13. if (typeof WeakMap !== 'function') return null;
  14. var cacheBabelInterop = new WeakMap();
  15. var cacheNodeInterop = new WeakMap();
  16. return (_getRequireWildcardCache = function (nodeInterop) {
  17. return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  18. })(nodeInterop);
  19. }
  20. function _interopRequireWildcard(obj, nodeInterop) {
  21. if (!nodeInterop && obj && obj.__esModule) {
  22. return obj;
  23. }
  24. if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
  25. return {default: obj};
  26. }
  27. var cache = _getRequireWildcardCache(nodeInterop);
  28. if (cache && cache.has(obj)) {
  29. return cache.get(obj);
  30. }
  31. var newObj = {};
  32. var hasPropertyDescriptor =
  33. Object.defineProperty && Object.getOwnPropertyDescriptor;
  34. for (var key in obj) {
  35. if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
  36. var desc = hasPropertyDescriptor
  37. ? Object.getOwnPropertyDescriptor(obj, key)
  38. : null;
  39. if (desc && (desc.get || desc.set)) {
  40. Object.defineProperty(newObj, key, desc);
  41. } else {
  42. newObj[key] = obj[key];
  43. }
  44. }
  45. }
  46. newObj.default = obj;
  47. if (cache) {
  48. cache.set(obj, newObj);
  49. }
  50. return newObj;
  51. }
  52. var global = (function () {
  53. if (typeof globalThis !== 'undefined') {
  54. return globalThis;
  55. } else if (typeof global !== 'undefined') {
  56. return global;
  57. } else if (typeof self !== 'undefined') {
  58. return self;
  59. } else if (typeof window !== 'undefined') {
  60. return window;
  61. } else {
  62. return Function('return this')();
  63. }
  64. })();
  65. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  66. var global = (function () {
  67. if (typeof globalThis !== 'undefined') {
  68. return globalThis;
  69. } else if (typeof global !== 'undefined') {
  70. return global;
  71. } else if (typeof self !== 'undefined') {
  72. return self;
  73. } else if (typeof window !== 'undefined') {
  74. return window;
  75. } else {
  76. return Function('return this')();
  77. }
  78. })();
  79. var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
  80. var global = (function () {
  81. if (typeof globalThis !== 'undefined') {
  82. return globalThis;
  83. } else if (typeof global !== 'undefined') {
  84. return global;
  85. } else if (typeof self !== 'undefined') {
  86. return self;
  87. } else if (typeof window !== 'undefined') {
  88. return window;
  89. } else {
  90. return Function('return this')();
  91. }
  92. })();
  93. var jestExistsFile =
  94. global[Symbol.for('jest-native-exists-file')] || fs.existsSync;
  95. const DID_NOT_THROW = 'Received function did not throw'; // same as toThrow
  96. const NOT_SNAPSHOT_MATCHERS = `Snapshot matchers cannot be used with ${(0,
  97. _jestMatcherUtils.BOLD_WEIGHT)('not')}`;
  98. const INDENTATION_REGEX = /^([^\S\n]*)\S/m; // Display name in report when matcher fails same as in snapshot file,
  99. // but with optional hint argument in bold weight.
  100. const printSnapshotName = (concatenatedBlockNames = '', hint = '', count) => {
  101. const hasNames = concatenatedBlockNames.length !== 0;
  102. const hasHint = hint.length !== 0;
  103. return (
  104. 'Snapshot name: `' +
  105. (hasNames ? utils.escapeBacktickString(concatenatedBlockNames) : '') +
  106. (hasNames && hasHint ? ': ' : '') +
  107. (hasHint
  108. ? (0, _jestMatcherUtils.BOLD_WEIGHT)(utils.escapeBacktickString(hint))
  109. : '') +
  110. ' ' +
  111. count +
  112. '`'
  113. );
  114. };
  115. function stripAddedIndentation(inlineSnapshot) {
  116. // Find indentation if exists.
  117. const match = inlineSnapshot.match(INDENTATION_REGEX);
  118. if (!match || !match[1]) {
  119. // No indentation.
  120. return inlineSnapshot;
  121. }
  122. const indentation = match[1];
  123. const lines = inlineSnapshot.split('\n');
  124. if (lines.length <= 2) {
  125. // Must be at least 3 lines.
  126. return inlineSnapshot;
  127. }
  128. if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') {
  129. // If not blank first and last lines, abort.
  130. return inlineSnapshot;
  131. }
  132. for (let i = 1; i < lines.length - 1; i++) {
  133. if (lines[i] !== '') {
  134. if (lines[i].indexOf(indentation) !== 0) {
  135. // All lines except first and last should either be blank or have the same
  136. // indent as the first line (or more). If this isn't the case we don't
  137. // want to touch the snapshot at all.
  138. return inlineSnapshot;
  139. }
  140. lines[i] = lines[i].substring(indentation.length);
  141. }
  142. } // Last line is a special case because it won't have the same indent as others
  143. // but may still have been given some indent to line up.
  144. lines[lines.length - 1] = ''; // Return inline snapshot, now at indent 0.
  145. inlineSnapshot = lines.join('\n');
  146. return inlineSnapshot;
  147. }
  148. const fileExists = (filePath, hasteFS) =>
  149. hasteFS.exists(filePath) || jestExistsFile(filePath);
  150. const cleanup = (hasteFS, update, snapshotResolver, testPathIgnorePatterns) => {
  151. const pattern = '\\.' + _SnapshotResolver.EXTENSION + '$';
  152. const files = hasteFS.matchFiles(pattern);
  153. let testIgnorePatternsRegex = null;
  154. if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) {
  155. testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|'));
  156. }
  157. const list = files.filter(snapshotFile => {
  158. const testPath = snapshotResolver.resolveTestPath(snapshotFile); // ignore snapshots of ignored tests
  159. if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) {
  160. return false;
  161. }
  162. if (!fileExists(testPath, hasteFS)) {
  163. if (update === 'all') {
  164. fs.unlinkSync(snapshotFile);
  165. }
  166. return true;
  167. }
  168. return false;
  169. });
  170. return {
  171. filesRemoved: list.length,
  172. filesRemovedList: list
  173. };
  174. };
  175. const toMatchSnapshot = function (received, propertiesOrHint, hint) {
  176. const matcherName = 'toMatchSnapshot';
  177. let properties;
  178. const length = arguments.length;
  179. if (length === 2 && typeof propertiesOrHint === 'string') {
  180. hint = propertiesOrHint;
  181. } else if (length >= 2) {
  182. if (typeof propertiesOrHint !== 'object' || propertiesOrHint === null) {
  183. const options = {
  184. isNot: this.isNot,
  185. promise: this.promise
  186. };
  187. let printedWithType = (0, _jestMatcherUtils.printWithType)(
  188. 'Expected properties',
  189. propertiesOrHint,
  190. _printSnapshot.printExpected
  191. );
  192. if (length === 3) {
  193. options.secondArgument = 'hint';
  194. options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT;
  195. if (propertiesOrHint == null) {
  196. printedWithType +=
  197. "\n\nTo provide a hint without properties: toMatchSnapshot('hint')";
  198. }
  199. }
  200. throw new Error(
  201. (0, _jestMatcherUtils.matcherErrorMessage)(
  202. (0, _jestMatcherUtils.matcherHint)(
  203. matcherName,
  204. undefined,
  205. _printSnapshot.PROPERTIES_ARG,
  206. options
  207. ),
  208. `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)(
  209. 'properties'
  210. )} must be an object`,
  211. printedWithType
  212. )
  213. );
  214. } // Future breaking change: Snapshot hint must be a string
  215. // if (arguments.length === 3 && typeof hint !== 'string') {}
  216. properties = propertiesOrHint;
  217. }
  218. return _toMatchSnapshot({
  219. context: this,
  220. hint,
  221. isInline: false,
  222. matcherName,
  223. properties,
  224. received
  225. });
  226. };
  227. const toMatchInlineSnapshot = function (
  228. received,
  229. propertiesOrSnapshot,
  230. inlineSnapshot
  231. ) {
  232. const matcherName = 'toMatchInlineSnapshot';
  233. let properties;
  234. const length = arguments.length;
  235. if (length === 2 && typeof propertiesOrSnapshot === 'string') {
  236. inlineSnapshot = propertiesOrSnapshot;
  237. } else if (length >= 2) {
  238. const options = {
  239. isNot: this.isNot,
  240. promise: this.promise
  241. };
  242. if (length === 3) {
  243. options.secondArgument = _printSnapshot.SNAPSHOT_ARG;
  244. options.secondArgumentColor = _printSnapshot.noColor;
  245. }
  246. if (
  247. typeof propertiesOrSnapshot !== 'object' ||
  248. propertiesOrSnapshot === null
  249. ) {
  250. throw new Error(
  251. (0, _jestMatcherUtils.matcherErrorMessage)(
  252. (0, _jestMatcherUtils.matcherHint)(
  253. matcherName,
  254. undefined,
  255. _printSnapshot.PROPERTIES_ARG,
  256. options
  257. ),
  258. `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)(
  259. 'properties'
  260. )} must be an object`,
  261. (0, _jestMatcherUtils.printWithType)(
  262. 'Expected properties',
  263. propertiesOrSnapshot,
  264. _printSnapshot.printExpected
  265. )
  266. )
  267. );
  268. }
  269. if (length === 3 && typeof inlineSnapshot !== 'string') {
  270. throw new Error(
  271. (0, _jestMatcherUtils.matcherErrorMessage)(
  272. (0, _jestMatcherUtils.matcherHint)(
  273. matcherName,
  274. undefined,
  275. _printSnapshot.PROPERTIES_ARG,
  276. options
  277. ),
  278. 'Inline snapshot must be a string',
  279. (0, _jestMatcherUtils.printWithType)(
  280. 'Inline snapshot',
  281. inlineSnapshot,
  282. utils.serialize
  283. )
  284. )
  285. );
  286. }
  287. properties = propertiesOrSnapshot;
  288. }
  289. return _toMatchSnapshot({
  290. context: this,
  291. inlineSnapshot:
  292. inlineSnapshot !== undefined
  293. ? stripAddedIndentation(inlineSnapshot)
  294. : undefined,
  295. isInline: true,
  296. matcherName,
  297. properties,
  298. received
  299. });
  300. };
  301. const _toMatchSnapshot = config => {
  302. const {context, hint, inlineSnapshot, isInline, matcherName, properties} =
  303. config;
  304. let {received} = config;
  305. context.dontThrow && context.dontThrow();
  306. const {currentTestName, isNot, snapshotState} = context;
  307. if (isNot) {
  308. throw new Error(
  309. (0, _jestMatcherUtils.matcherErrorMessage)(
  310. (0, _printSnapshot.matcherHintFromConfig)(config, false),
  311. NOT_SNAPSHOT_MATCHERS
  312. )
  313. );
  314. }
  315. if (snapshotState == null) {
  316. // Because the state is the problem, this is not a matcher error.
  317. // Call generic stringify from jest-matcher-utils package
  318. // because uninitialized snapshot state does not need snapshot serializers.
  319. throw new Error(
  320. (0, _printSnapshot.matcherHintFromConfig)(config, false) +
  321. '\n\n' +
  322. 'Snapshot state must be initialized' +
  323. '\n\n' +
  324. (0, _jestMatcherUtils.printWithType)(
  325. 'Snapshot state',
  326. snapshotState,
  327. _jestMatcherUtils.stringify
  328. )
  329. );
  330. }
  331. const fullTestName =
  332. currentTestName && hint
  333. ? `${currentTestName}: ${hint}`
  334. : currentTestName || ''; // future BREAKING change: || hint
  335. if (typeof properties === 'object') {
  336. if (typeof received !== 'object' || received === null) {
  337. throw new Error(
  338. (0, _jestMatcherUtils.matcherErrorMessage)(
  339. (0, _printSnapshot.matcherHintFromConfig)(config, false),
  340. `${(0, _jestMatcherUtils.RECEIVED_COLOR)(
  341. 'received'
  342. )} value must be an object when the matcher has ${(0,
  343. _jestMatcherUtils.EXPECTED_COLOR)('properties')}`,
  344. (0, _jestMatcherUtils.printWithType)(
  345. 'Received',
  346. received,
  347. _printSnapshot.printReceived
  348. )
  349. )
  350. );
  351. }
  352. const propertyPass = context.equals(received, properties, [
  353. context.utils.iterableEquality,
  354. context.utils.subsetEquality
  355. ]);
  356. if (!propertyPass) {
  357. const key = snapshotState.fail(fullTestName, received);
  358. const matched = /(\d+)$/.exec(key);
  359. const count = matched === null ? 1 : Number(matched[1]);
  360. const message = () =>
  361. (0, _printSnapshot.matcherHintFromConfig)(config, false) +
  362. '\n\n' +
  363. printSnapshotName(currentTestName, hint, count) +
  364. '\n\n' +
  365. (0, _printSnapshot.printPropertiesAndReceived)(
  366. properties,
  367. received,
  368. snapshotState.expand
  369. );
  370. return {
  371. message,
  372. name: matcherName,
  373. pass: false
  374. };
  375. } else {
  376. received = utils.deepMerge(received, properties);
  377. }
  378. }
  379. const result = snapshotState.match({
  380. error: context.error,
  381. inlineSnapshot,
  382. isInline,
  383. received,
  384. testName: fullTestName
  385. });
  386. const {actual, count, expected, pass} = result;
  387. if (pass) {
  388. return {
  389. message: () => '',
  390. pass: true
  391. };
  392. }
  393. const message =
  394. expected === undefined
  395. ? () =>
  396. (0, _printSnapshot.matcherHintFromConfig)(config, true) +
  397. '\n\n' +
  398. printSnapshotName(currentTestName, hint, count) +
  399. '\n\n' +
  400. `New snapshot was ${(0, _jestMatcherUtils.BOLD_WEIGHT)(
  401. 'not written'
  402. )}. The update flag ` +
  403. 'must be explicitly passed to write a new snapshot.\n\n' +
  404. 'This is likely because this test is run in a continuous integration ' +
  405. '(CI) environment in which snapshots are not written by default.\n\n' +
  406. `Received:${actual.includes('\n') ? '\n' : ' '}${(0,
  407. _printSnapshot.bReceivedColor)(actual)}`
  408. : () =>
  409. (0, _printSnapshot.matcherHintFromConfig)(config, true) +
  410. '\n\n' +
  411. printSnapshotName(currentTestName, hint, count) +
  412. '\n\n' +
  413. (0, _printSnapshot.printSnapshotAndReceived)(
  414. expected,
  415. actual,
  416. received,
  417. snapshotState.expand
  418. ); // Passing the actual and expected objects so that a custom reporter
  419. // could access them, for example in order to display a custom visual diff,
  420. // or create a different error message
  421. return {
  422. actual,
  423. expected,
  424. message,
  425. name: matcherName,
  426. pass: false
  427. };
  428. };
  429. const toThrowErrorMatchingSnapshot = function (
  430. received,
  431. hint, // because error TS1016 for hint?: string
  432. fromPromise
  433. ) {
  434. const matcherName = 'toThrowErrorMatchingSnapshot'; // Future breaking change: Snapshot hint must be a string
  435. // if (hint !== undefined && typeof hint !== string) {}
  436. return _toThrowErrorMatchingSnapshot(
  437. {
  438. context: this,
  439. hint,
  440. isInline: false,
  441. matcherName,
  442. received
  443. },
  444. fromPromise
  445. );
  446. };
  447. const toThrowErrorMatchingInlineSnapshot = function (
  448. received,
  449. inlineSnapshot,
  450. fromPromise
  451. ) {
  452. const matcherName = 'toThrowErrorMatchingInlineSnapshot';
  453. if (inlineSnapshot !== undefined && typeof inlineSnapshot !== 'string') {
  454. const options = {
  455. expectedColor: _printSnapshot.noColor,
  456. isNot: this.isNot,
  457. promise: this.promise
  458. };
  459. throw new Error(
  460. (0, _jestMatcherUtils.matcherErrorMessage)(
  461. (0, _jestMatcherUtils.matcherHint)(
  462. matcherName,
  463. undefined,
  464. _printSnapshot.SNAPSHOT_ARG,
  465. options
  466. ),
  467. 'Inline snapshot must be a string',
  468. (0, _jestMatcherUtils.printWithType)(
  469. 'Inline snapshot',
  470. inlineSnapshot,
  471. utils.serialize
  472. )
  473. )
  474. );
  475. }
  476. return _toThrowErrorMatchingSnapshot(
  477. {
  478. context: this,
  479. inlineSnapshot:
  480. inlineSnapshot !== undefined
  481. ? stripAddedIndentation(inlineSnapshot)
  482. : undefined,
  483. isInline: true,
  484. matcherName,
  485. received
  486. },
  487. fromPromise
  488. );
  489. };
  490. const _toThrowErrorMatchingSnapshot = (config, fromPromise) => {
  491. const {context, hint, inlineSnapshot, isInline, matcherName, received} =
  492. config;
  493. context.dontThrow && context.dontThrow();
  494. const {isNot, promise} = context;
  495. if (!fromPromise) {
  496. if (typeof received !== 'function') {
  497. const options = {
  498. isNot,
  499. promise
  500. };
  501. throw new Error(
  502. (0, _jestMatcherUtils.matcherErrorMessage)(
  503. (0, _jestMatcherUtils.matcherHint)(
  504. matcherName,
  505. undefined,
  506. '',
  507. options
  508. ),
  509. `${(0, _jestMatcherUtils.RECEIVED_COLOR)(
  510. 'received'
  511. )} value must be a function`,
  512. (0, _jestMatcherUtils.printWithType)(
  513. 'Received',
  514. received,
  515. _printSnapshot.printReceived
  516. )
  517. )
  518. );
  519. }
  520. }
  521. if (isNot) {
  522. throw new Error(
  523. (0, _jestMatcherUtils.matcherErrorMessage)(
  524. (0, _printSnapshot.matcherHintFromConfig)(config, false),
  525. NOT_SNAPSHOT_MATCHERS
  526. )
  527. );
  528. }
  529. let error;
  530. if (fromPromise) {
  531. error = received;
  532. } else {
  533. try {
  534. received();
  535. } catch (e) {
  536. error = e;
  537. }
  538. }
  539. if (error === undefined) {
  540. // Because the received value is a function, this is not a matcher error.
  541. throw new Error(
  542. (0, _printSnapshot.matcherHintFromConfig)(config, false) +
  543. '\n\n' +
  544. DID_NOT_THROW
  545. );
  546. }
  547. return _toMatchSnapshot({
  548. context,
  549. hint,
  550. inlineSnapshot,
  551. isInline,
  552. matcherName,
  553. received: error.message
  554. });
  555. };
  556. const JestSnapshot = {
  557. EXTENSION: _SnapshotResolver.EXTENSION,
  558. SnapshotState: _State.default,
  559. addSerializer: _plugins.addSerializer,
  560. buildSnapshotResolver: _SnapshotResolver.buildSnapshotResolver,
  561. cleanup,
  562. getSerializers: _plugins.getSerializers,
  563. isSnapshotPath: _SnapshotResolver.isSnapshotPath,
  564. toMatchInlineSnapshot,
  565. toMatchSnapshot,
  566. toThrowErrorMatchingInlineSnapshot,
  567. toThrowErrorMatchingSnapshot,
  568. utils
  569. };
  570. module.exports = JestSnapshot;