index.js 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  1. /*!
  2. * /**
  3. * * Copyright (c) Meta Platforms, Inc. and affiliates.
  4. * *
  5. * * This source code is licensed under the MIT license found in the
  6. * * LICENSE file in the root directory of this source tree.
  7. * * /
  8. */
  9. /******/ (() => { // webpackBootstrap
  10. /******/ "use strict";
  11. /******/ var __webpack_modules__ = ({
  12. /***/ "./src/asymmetricMatchers.ts":
  13. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  14. Object.defineProperty(exports, "__esModule", ({
  15. value: true
  16. }));
  17. exports.closeTo = exports.arrayOf = exports.arrayNotContaining = exports.arrayContaining = exports.anything = exports.any = exports.AsymmetricMatcher = void 0;
  18. exports.hasProperty = hasProperty;
  19. exports.stringNotMatching = exports.stringNotContaining = exports.stringMatching = exports.stringContaining = exports.objectNotContaining = exports.objectContaining = exports.notCloseTo = exports.notArrayOf = void 0;
  20. var _expectUtils = require("@jest/expect-utils");
  21. var matcherUtils = _interopRequireWildcard(require("jest-matcher-utils"));
  22. var _jestUtil = require("jest-util");
  23. var _jestMatchersObject = __webpack_require__("./src/jestMatchersObject.ts");
  24. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
  25. var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
  26. /**
  27. * Copyright (c) Meta Platforms, Inc. and affiliates.
  28. *
  29. * This source code is licensed under the MIT license found in the
  30. * LICENSE file in the root directory of this source tree.
  31. *
  32. */
  33. const functionToString = Function.prototype.toString;
  34. function fnNameFor(func) {
  35. if (func.name) {
  36. return func.name;
  37. }
  38. const matches = functionToString.call(func).match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
  39. return matches ? matches[1] : '<anonymous>';
  40. }
  41. const utils = Object.freeze({
  42. ...matcherUtils,
  43. iterableEquality: _expectUtils.iterableEquality,
  44. subsetEquality: _expectUtils.subsetEquality
  45. });
  46. function hasProperty(obj, property) {
  47. if (!obj) {
  48. return false;
  49. }
  50. if (Object.prototype.hasOwnProperty.call(obj, property)) {
  51. return true;
  52. }
  53. return hasProperty(Object.getPrototypeOf(obj), property);
  54. }
  55. class AsymmetricMatcher {
  56. $$typeof = Symbol.for('jest.asymmetricMatcher');
  57. constructor(sample, inverse = false) {
  58. this.sample = sample;
  59. this.inverse = inverse;
  60. }
  61. getMatcherContext() {
  62. return {
  63. customTesters: (0, _jestMatchersObject.getCustomEqualityTesters)(),
  64. // eslint-disable-next-line @typescript-eslint/no-empty-function
  65. dontThrow: () => {},
  66. ...(0, _jestMatchersObject.getState)(),
  67. equals: _expectUtils.equals,
  68. isNot: this.inverse,
  69. utils
  70. };
  71. }
  72. }
  73. exports.AsymmetricMatcher = AsymmetricMatcher;
  74. class Any extends AsymmetricMatcher {
  75. constructor(sample) {
  76. if (sample === undefined) {
  77. throw new TypeError('any() expects to be passed a constructor function. ' + 'Please pass one or use anything() to match any object.');
  78. }
  79. super(sample);
  80. }
  81. asymmetricMatch(other) {
  82. if (this.sample === String) {
  83. // eslint-disable-next-line unicorn/no-instanceof-builtins
  84. return typeof other === 'string' || other instanceof String;
  85. }
  86. if (this.sample === Number) {
  87. // eslint-disable-next-line unicorn/no-instanceof-builtins
  88. return typeof other === 'number' || other instanceof Number;
  89. }
  90. if (this.sample === Function) {
  91. // eslint-disable-next-line unicorn/no-instanceof-builtins
  92. return typeof other === 'function' || other instanceof Function;
  93. }
  94. if (this.sample === Boolean) {
  95. // eslint-disable-next-line unicorn/no-instanceof-builtins
  96. return typeof other === 'boolean' || other instanceof Boolean;
  97. }
  98. if (this.sample === BigInt) {
  99. // eslint-disable-next-line unicorn/no-instanceof-builtins
  100. return typeof other === 'bigint' || other instanceof BigInt;
  101. }
  102. if (this.sample === Symbol) {
  103. // eslint-disable-next-line unicorn/no-instanceof-builtins
  104. return typeof other === 'symbol' || other instanceof Symbol;
  105. }
  106. if (this.sample === Object) {
  107. return typeof other === 'object';
  108. }
  109. if (this.sample === Array) {
  110. return Array.isArray(other);
  111. }
  112. return other instanceof this.sample;
  113. }
  114. toString() {
  115. return 'Any';
  116. }
  117. getExpectedType() {
  118. if (this.sample === String) {
  119. return 'string';
  120. }
  121. if (this.sample === Number) {
  122. return 'number';
  123. }
  124. if (this.sample === Function) {
  125. return 'function';
  126. }
  127. if (this.sample === Object) {
  128. return 'object';
  129. }
  130. if (this.sample === Boolean) {
  131. return 'boolean';
  132. }
  133. if (this.sample === Array) {
  134. return 'array';
  135. }
  136. return fnNameFor(this.sample);
  137. }
  138. toAsymmetricMatcher() {
  139. return `Any<${fnNameFor(this.sample)}>`;
  140. }
  141. }
  142. class Anything extends AsymmetricMatcher {
  143. asymmetricMatch(other) {
  144. return other != null;
  145. }
  146. toString() {
  147. return 'Anything';
  148. }
  149. // No getExpectedType method, because it matches either null or undefined.
  150. toAsymmetricMatcher() {
  151. return 'Anything';
  152. }
  153. }
  154. class ArrayContaining extends AsymmetricMatcher {
  155. constructor(sample, inverse = false) {
  156. super(sample, inverse);
  157. }
  158. asymmetricMatch(other) {
  159. if (!Array.isArray(this.sample)) {
  160. throw new TypeError(`You must provide an array to ${this.toString()}, not '${typeof this.sample}'.`);
  161. }
  162. const matcherContext = this.getMatcherContext();
  163. const result = this.sample.length === 0 || Array.isArray(other) && this.sample.every(item => other.some(another => (0, _expectUtils.equals)(item, another, matcherContext.customTesters)));
  164. return this.inverse ? !result : result;
  165. }
  166. toString() {
  167. return `Array${this.inverse ? 'Not' : ''}Containing`;
  168. }
  169. getExpectedType() {
  170. return 'array';
  171. }
  172. }
  173. class ArrayOf extends AsymmetricMatcher {
  174. asymmetricMatch(other) {
  175. const matcherContext = this.getMatcherContext();
  176. const result = Array.isArray(other) && other.every(item => (0, _expectUtils.equals)(this.sample, item, matcherContext.customTesters));
  177. return this.inverse ? !result : result;
  178. }
  179. toString() {
  180. return `${this.inverse ? 'Not' : ''}ArrayOf`;
  181. }
  182. getExpectedType() {
  183. return 'array';
  184. }
  185. }
  186. class ObjectContaining extends AsymmetricMatcher {
  187. constructor(sample, inverse = false) {
  188. super(sample, inverse);
  189. }
  190. asymmetricMatch(other) {
  191. // Ensures that the argument passed to the objectContaining method is an object
  192. if (typeof this.sample !== 'object') {
  193. throw new TypeError(`You must provide an object to ${this.toString()}, not '${typeof this.sample}'.`);
  194. }
  195. // Ensures that the argument passed to the expect function is an object
  196. // This is necessary to avoid matching of non-object values
  197. // Arrays are a special type of object, but having a valid match with a standard object
  198. // does not make sense, hence we do a simple array check
  199. if (typeof other !== 'object' || Array.isArray(other)) {
  200. return false;
  201. }
  202. let result = true;
  203. const matcherContext = this.getMatcherContext();
  204. const objectKeys = (0, _expectUtils.getObjectKeys)(this.sample);
  205. for (const key of objectKeys) {
  206. if (!hasProperty(other, key) || !(0, _expectUtils.equals)(this.sample[key], other[key], matcherContext.customTesters)) {
  207. result = false;
  208. break;
  209. }
  210. }
  211. return this.inverse ? !result : result;
  212. }
  213. toString() {
  214. return `Object${this.inverse ? 'Not' : ''}Containing`;
  215. }
  216. getExpectedType() {
  217. return 'object';
  218. }
  219. }
  220. class StringContaining extends AsymmetricMatcher {
  221. constructor(sample, inverse = false) {
  222. if (!(0, _expectUtils.isA)('String', sample)) {
  223. throw new Error('Expected is not a string');
  224. }
  225. super(sample, inverse);
  226. }
  227. asymmetricMatch(other) {
  228. const result = (0, _expectUtils.isA)('String', other) && other.includes(this.sample);
  229. return this.inverse ? !result : result;
  230. }
  231. toString() {
  232. return `String${this.inverse ? 'Not' : ''}Containing`;
  233. }
  234. getExpectedType() {
  235. return 'string';
  236. }
  237. }
  238. class StringMatching extends AsymmetricMatcher {
  239. constructor(sample, inverse = false) {
  240. if (!(0, _expectUtils.isA)('String', sample) && !(0, _expectUtils.isA)('RegExp', sample)) {
  241. throw new Error('Expected is not a String or a RegExp');
  242. }
  243. super(new RegExp(sample), inverse);
  244. }
  245. asymmetricMatch(other) {
  246. const result = (0, _expectUtils.isA)('String', other) && this.sample.test(other);
  247. return this.inverse ? !result : result;
  248. }
  249. toString() {
  250. return `String${this.inverse ? 'Not' : ''}Matching`;
  251. }
  252. getExpectedType() {
  253. return 'string';
  254. }
  255. }
  256. class CloseTo extends AsymmetricMatcher {
  257. precision;
  258. constructor(sample, precision = 2, inverse = false) {
  259. if (!(0, _expectUtils.isA)('Number', sample)) {
  260. throw new Error('Expected is not a Number');
  261. }
  262. if (!(0, _expectUtils.isA)('Number', precision)) {
  263. throw new Error('Precision is not a Number');
  264. }
  265. super(sample);
  266. this.inverse = inverse;
  267. this.precision = precision;
  268. }
  269. asymmetricMatch(other) {
  270. if (!(0, _expectUtils.isA)('Number', other)) {
  271. return false;
  272. }
  273. let result = false;
  274. if (other === Number.POSITIVE_INFINITY && this.sample === Number.POSITIVE_INFINITY) {
  275. result = true; // Infinity - Infinity is NaN
  276. } else if (other === Number.NEGATIVE_INFINITY && this.sample === Number.NEGATIVE_INFINITY) {
  277. result = true; // -Infinity - -Infinity is NaN
  278. } else {
  279. result = Math.abs(this.sample - other) < Math.pow(10, -this.precision) / 2;
  280. }
  281. return this.inverse ? !result : result;
  282. }
  283. toString() {
  284. return `Number${this.inverse ? 'Not' : ''}CloseTo`;
  285. }
  286. getExpectedType() {
  287. return 'number';
  288. }
  289. toAsymmetricMatcher() {
  290. return [this.toString(), this.sample, `(${(0, _jestUtil.pluralize)('digit', this.precision)})`].join(' ');
  291. }
  292. }
  293. const any = expectedObject => new Any(expectedObject);
  294. exports.any = any;
  295. const anything = () => new Anything();
  296. exports.anything = anything;
  297. const arrayContaining = sample => new ArrayContaining(sample);
  298. exports.arrayContaining = arrayContaining;
  299. const arrayNotContaining = sample => new ArrayContaining(sample, true);
  300. exports.arrayNotContaining = arrayNotContaining;
  301. const arrayOf = sample => new ArrayOf(sample);
  302. exports.arrayOf = arrayOf;
  303. const notArrayOf = sample => new ArrayOf(sample, true);
  304. exports.notArrayOf = notArrayOf;
  305. const objectContaining = sample => new ObjectContaining(sample);
  306. exports.objectContaining = objectContaining;
  307. const objectNotContaining = sample => new ObjectContaining(sample, true);
  308. exports.objectNotContaining = objectNotContaining;
  309. const stringContaining = expected => new StringContaining(expected);
  310. exports.stringContaining = stringContaining;
  311. const stringNotContaining = expected => new StringContaining(expected, true);
  312. exports.stringNotContaining = stringNotContaining;
  313. const stringMatching = expected => new StringMatching(expected);
  314. exports.stringMatching = stringMatching;
  315. const stringNotMatching = expected => new StringMatching(expected, true);
  316. exports.stringNotMatching = stringNotMatching;
  317. const closeTo = (expected, precision) => new CloseTo(expected, precision);
  318. exports.closeTo = closeTo;
  319. const notCloseTo = (expected, precision) => new CloseTo(expected, precision, true);
  320. exports.notCloseTo = notCloseTo;
  321. /***/ }),
  322. /***/ "./src/extractExpectedAssertionsErrors.ts":
  323. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  324. Object.defineProperty(exports, "__esModule", ({
  325. value: true
  326. }));
  327. exports["default"] = void 0;
  328. var _jestMatcherUtils = require("jest-matcher-utils");
  329. var _jestMatchersObject = __webpack_require__("./src/jestMatchersObject.ts");
  330. /**
  331. * Copyright (c) Meta Platforms, Inc. and affiliates.
  332. *
  333. * This source code is licensed under the MIT license found in the
  334. * LICENSE file in the root directory of this source tree.
  335. *
  336. */
  337. const resetAssertionsLocalState = () => {
  338. (0, _jestMatchersObject.setState)({
  339. assertionCalls: 0,
  340. expectedAssertionsNumber: null,
  341. isExpectingAssertions: false,
  342. numPassingAsserts: 0
  343. });
  344. };
  345. // Create and format all errors related to the mismatched number of `expect`
  346. // calls and reset the matcher's state.
  347. const extractExpectedAssertionsErrors = () => {
  348. const result = [];
  349. const {
  350. assertionCalls,
  351. expectedAssertionsNumber,
  352. expectedAssertionsNumberError,
  353. isExpectingAssertions,
  354. isExpectingAssertionsError
  355. } = (0, _jestMatchersObject.getState)();
  356. resetAssertionsLocalState();
  357. if (typeof expectedAssertionsNumber === 'number' && assertionCalls !== expectedAssertionsNumber) {
  358. const numOfAssertionsExpected = (0, _jestMatcherUtils.EXPECTED_COLOR)((0, _jestMatcherUtils.pluralize)('assertion', expectedAssertionsNumber));
  359. expectedAssertionsNumberError.message = `${(0, _jestMatcherUtils.matcherHint)('.assertions', '', expectedAssertionsNumber.toString(), {
  360. isDirectExpectCall: true
  361. })}\n\n` + `Expected ${numOfAssertionsExpected} to be called but received ${(0, _jestMatcherUtils.RECEIVED_COLOR)((0, _jestMatcherUtils.pluralize)('assertion call', assertionCalls || 0))}.`;
  362. result.push({
  363. actual: assertionCalls.toString(),
  364. error: expectedAssertionsNumberError,
  365. expected: expectedAssertionsNumber.toString()
  366. });
  367. }
  368. if (isExpectingAssertions && assertionCalls === 0) {
  369. const expected = (0, _jestMatcherUtils.EXPECTED_COLOR)('at least one assertion');
  370. const received = (0, _jestMatcherUtils.RECEIVED_COLOR)('received none');
  371. isExpectingAssertionsError.message = `${(0, _jestMatcherUtils.matcherHint)('.hasAssertions', '', '', {
  372. isDirectExpectCall: true
  373. })}\n\nExpected ${expected} to be called but ${received}.`;
  374. result.push({
  375. actual: 'none',
  376. error: isExpectingAssertionsError,
  377. expected: 'at least one'
  378. });
  379. }
  380. return result;
  381. };
  382. var _default = exports["default"] = extractExpectedAssertionsErrors;
  383. /***/ }),
  384. /***/ "./src/jestMatchersObject.ts":
  385. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  386. Object.defineProperty(exports, "__esModule", ({
  387. value: true
  388. }));
  389. exports.setState = exports.setMatchers = exports.getState = exports.getMatchers = exports.getCustomEqualityTesters = exports.addCustomEqualityTesters = exports.INTERNAL_MATCHER_FLAG = void 0;
  390. var _getType = require("@jest/get-type");
  391. var _asymmetricMatchers = __webpack_require__("./src/asymmetricMatchers.ts");
  392. var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol;
  393. /**
  394. * Copyright (c) Meta Platforms, Inc. and affiliates.
  395. *
  396. * This source code is licensed under the MIT license found in the
  397. * LICENSE file in the root directory of this source tree.
  398. *
  399. */
  400. // Global matchers object holds the list of available matchers and
  401. // the state, that can hold matcher specific values that change over time.
  402. const JEST_MATCHERS_OBJECT = Symbol.for('$$jest-matchers-object');
  403. // Notes a built-in/internal Jest matcher.
  404. // Jest may override the stack trace of Errors thrown by internal matchers.
  405. const INTERNAL_MATCHER_FLAG = exports.INTERNAL_MATCHER_FLAG = Symbol.for('$$jest-internal-matcher');
  406. if (!Object.prototype.hasOwnProperty.call(globalThis, JEST_MATCHERS_OBJECT)) {
  407. const defaultState = {
  408. assertionCalls: 0,
  409. expectedAssertionsNumber: null,
  410. isExpectingAssertions: false,
  411. numPassingAsserts: 0,
  412. suppressedErrors: [] // errors that are not thrown immediately.
  413. };
  414. Object.defineProperty(globalThis, JEST_MATCHERS_OBJECT, {
  415. value: {
  416. customEqualityTesters: [],
  417. matchers: Object.create(null),
  418. state: defaultState
  419. }
  420. });
  421. }
  422. const getState = () => globalThis[JEST_MATCHERS_OBJECT].state;
  423. exports.getState = getState;
  424. const setState = state => {
  425. Object.assign(globalThis[JEST_MATCHERS_OBJECT].state, state);
  426. };
  427. exports.setState = setState;
  428. const getMatchers = () => globalThis[JEST_MATCHERS_OBJECT].matchers;
  429. exports.getMatchers = getMatchers;
  430. const setMatchers = (matchers, isInternal, expect) => {
  431. for (const key of Object.keys(matchers)) {
  432. const matcher = matchers[key];
  433. if (typeof matcher !== 'function') {
  434. throw new TypeError(`expect.extend: \`${key}\` is not a valid matcher. Must be a function, is "${(0, _getType.getType)(matcher)}"`);
  435. }
  436. Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, {
  437. value: isInternal
  438. });
  439. if (!isInternal) {
  440. // expect is defined
  441. class CustomMatcher extends _asymmetricMatchers.AsymmetricMatcher {
  442. constructor(inverse = false, ...sample) {
  443. super(sample, inverse);
  444. }
  445. asymmetricMatch(other) {
  446. const {
  447. pass
  448. } = matcher.call(this.getMatcherContext(), other, ...this.sample);
  449. return this.inverse ? !pass : pass;
  450. }
  451. toString() {
  452. return `${this.inverse ? 'not.' : ''}${key}`;
  453. }
  454. getExpectedType() {
  455. return 'any';
  456. }
  457. toAsymmetricMatcher() {
  458. return `${this.toString()}<${this.sample.map(String).join(', ')}>`;
  459. }
  460. }
  461. Object.defineProperty(expect, key, {
  462. configurable: true,
  463. enumerable: true,
  464. value: (...sample) => new CustomMatcher(false, ...sample),
  465. writable: true
  466. });
  467. Object.defineProperty(expect.not, key, {
  468. configurable: true,
  469. enumerable: true,
  470. value: (...sample) => new CustomMatcher(true, ...sample),
  471. writable: true
  472. });
  473. }
  474. }
  475. Object.assign(globalThis[JEST_MATCHERS_OBJECT].matchers, matchers);
  476. };
  477. exports.setMatchers = setMatchers;
  478. const getCustomEqualityTesters = () => globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters;
  479. exports.getCustomEqualityTesters = getCustomEqualityTesters;
  480. const addCustomEqualityTesters = newTesters => {
  481. if (!Array.isArray(newTesters)) {
  482. throw new TypeError(`expect.customEqualityTesters: Must be set to an array of Testers. Was given "${(0, _getType.getType)(newTesters)}"`);
  483. }
  484. globalThis[JEST_MATCHERS_OBJECT].customEqualityTesters.push(...newTesters);
  485. };
  486. exports.addCustomEqualityTesters = addCustomEqualityTesters;
  487. /***/ }),
  488. /***/ "./src/matchers.ts":
  489. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  490. Object.defineProperty(exports, "__esModule", ({
  491. value: true
  492. }));
  493. exports["default"] = void 0;
  494. var _expectUtils = require("@jest/expect-utils");
  495. var _getType = require("@jest/get-type");
  496. var _jestMatcherUtils = require("jest-matcher-utils");
  497. var _print = __webpack_require__("./src/print.ts");
  498. /**
  499. * Copyright (c) Meta Platforms, Inc. and affiliates.
  500. *
  501. * This source code is licensed under the MIT license found in the
  502. * LICENSE file in the root directory of this source tree.
  503. *
  504. */
  505. // Omit colon and one or more spaces, so can call getLabelPrinter.
  506. const EXPECTED_LABEL = 'Expected';
  507. const RECEIVED_LABEL = 'Received';
  508. const EXPECTED_VALUE_LABEL = 'Expected value';
  509. const RECEIVED_VALUE_LABEL = 'Received value';
  510. // The optional property of matcher context is true if undefined.
  511. const isExpand = expand => expand !== false;
  512. const toStrictEqualTesters = [_expectUtils.iterableEquality, _expectUtils.typeEquality, _expectUtils.sparseArrayEquality, _expectUtils.arrayBufferEquality];
  513. const matchers = {
  514. toBe(received, expected) {
  515. const matcherName = 'toBe';
  516. const options = {
  517. comment: 'Object.is equality',
  518. isNot: this.isNot,
  519. promise: this.promise
  520. };
  521. const pass = Object.is(received, expected);
  522. const message = pass ? () =>
  523. // eslint-disable-next-line prefer-template
  524. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}` : () => {
  525. const expectedType = (0, _getType.getType)(expected);
  526. let deepEqualityName = null;
  527. if (expectedType !== 'map' && expectedType !== 'set') {
  528. // If deep equality passes when referential identity fails,
  529. // but exclude map and set until review of their equality logic.
  530. if ((0, _expectUtils.equals)(received, expected, [...this.customTesters, ...toStrictEqualTesters], true)) {
  531. deepEqualityName = 'toStrictEqual';
  532. } else if ((0, _expectUtils.equals)(received, expected, [...this.customTesters, _expectUtils.iterableEquality])) {
  533. deepEqualityName = 'toEqual';
  534. }
  535. }
  536. return (
  537. // eslint-disable-next-line prefer-template
  538. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (deepEqualityName === null ? '' : `${(0, _jestMatcherUtils.DIM_COLOR)(`If it should pass with deep equality, replace "${matcherName}" with "${deepEqualityName}"`)}\n\n`) + (0, _jestMatcherUtils.printDiffOrStringify)(expected, received, EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand))
  539. );
  540. };
  541. // Passing the actual and expected objects so that a custom reporter
  542. // could access them, for example in order to display a custom visual diff,
  543. // or create a different error message
  544. return {
  545. actual: received,
  546. expected,
  547. message,
  548. name: matcherName,
  549. pass
  550. };
  551. },
  552. toBeCloseTo(received, expected, precision = 2) {
  553. const matcherName = 'toBeCloseTo';
  554. const secondArgument = arguments.length === 3 ? 'precision' : undefined;
  555. const isNot = this.isNot;
  556. const options = {
  557. isNot,
  558. promise: this.promise,
  559. secondArgument,
  560. secondArgumentColor: arg => arg
  561. };
  562. if (typeof expected !== 'number') {
  563. throw new TypeError((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} value must be a number`, (0, _jestMatcherUtils.printWithType)('Expected', expected, _jestMatcherUtils.printExpected)));
  564. }
  565. if (typeof received !== 'number') {
  566. throw new TypeError((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must be a number`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  567. }
  568. let pass = false;
  569. let expectedDiff = 0;
  570. let receivedDiff = 0;
  571. if (received === Number.POSITIVE_INFINITY && expected === Number.POSITIVE_INFINITY) {
  572. pass = true; // Infinity - Infinity is NaN
  573. } else if (received === Number.NEGATIVE_INFINITY && expected === Number.NEGATIVE_INFINITY) {
  574. pass = true; // -Infinity - -Infinity is NaN
  575. } else {
  576. expectedDiff = Math.pow(10, -precision) / 2;
  577. receivedDiff = Math.abs(expected - received);
  578. pass = receivedDiff < expectedDiff;
  579. }
  580. const message = pass ? () =>
  581. // eslint-disable-next-line prefer-template
  582. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + (receivedDiff === 0 ? '' : `Received: ${(0, _jestMatcherUtils.printReceived)(received)}\n` + `\n${(0, _print.printCloseTo)(receivedDiff, expectedDiff, precision, isNot)}`) : () =>
  583. // eslint-disable-next-line prefer-template
  584. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received: ${(0, _jestMatcherUtils.printReceived)(received)}\n` + '\n' + (0, _print.printCloseTo)(receivedDiff, expectedDiff, precision, isNot);
  585. return {
  586. message,
  587. pass
  588. };
  589. },
  590. toBeDefined(received, expected) {
  591. const matcherName = 'toBeDefined';
  592. const options = {
  593. isNot: this.isNot,
  594. promise: this.promise
  595. };
  596. (0, _jestMatcherUtils.ensureNoExpected)(expected, matcherName, options);
  597. const pass = received !== void 0;
  598. const message = () =>
  599. // eslint-disable-next-line prefer-template
  600. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`;
  601. return {
  602. message,
  603. pass
  604. };
  605. },
  606. toBeFalsy(received, expected) {
  607. const matcherName = 'toBeFalsy';
  608. const options = {
  609. isNot: this.isNot,
  610. promise: this.promise
  611. };
  612. (0, _jestMatcherUtils.ensureNoExpected)(expected, matcherName, options);
  613. const pass = !received;
  614. const message = () =>
  615. // eslint-disable-next-line prefer-template
  616. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`;
  617. return {
  618. message,
  619. pass
  620. };
  621. },
  622. toBeGreaterThan(received, expected) {
  623. const matcherName = 'toBeGreaterThan';
  624. const isNot = this.isNot;
  625. const options = {
  626. isNot,
  627. promise: this.promise
  628. };
  629. (0, _jestMatcherUtils.ensureNumbers)(received, expected, matcherName, options);
  630. const pass = received > expected;
  631. const message = () =>
  632. // eslint-disable-next-line prefer-template
  633. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected:${isNot ? ' not' : ''} > ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received:${isNot ? ' ' : ''} ${(0, _jestMatcherUtils.printReceived)(received)}`;
  634. return {
  635. message,
  636. pass
  637. };
  638. },
  639. toBeGreaterThanOrEqual(received, expected) {
  640. const matcherName = 'toBeGreaterThanOrEqual';
  641. const isNot = this.isNot;
  642. const options = {
  643. isNot,
  644. promise: this.promise
  645. };
  646. (0, _jestMatcherUtils.ensureNumbers)(received, expected, matcherName, options);
  647. const pass = received >= expected;
  648. const message = () =>
  649. // eslint-disable-next-line prefer-template
  650. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected:${isNot ? ' not' : ''} >= ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received:${isNot ? ' ' : ''} ${(0, _jestMatcherUtils.printReceived)(received)}`;
  651. return {
  652. message,
  653. pass
  654. };
  655. },
  656. toBeInstanceOf(received, expected) {
  657. const matcherName = 'toBeInstanceOf';
  658. const options = {
  659. isNot: this.isNot,
  660. promise: this.promise
  661. };
  662. if (typeof expected !== 'function') {
  663. throw new TypeError((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} value must be a function`, (0, _jestMatcherUtils.printWithType)('Expected', expected, _jestMatcherUtils.printExpected)));
  664. }
  665. const pass = received instanceof expected;
  666. const message = pass ? () =>
  667. // eslint-disable-next-line prefer-template
  668. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (0, _print.printExpectedConstructorNameNot)('Expected constructor', expected) + (typeof received.constructor === 'function' && received.constructor !== expected ? (0, _print.printReceivedConstructorNameNot)('Received constructor', received.constructor, expected) : '') : () =>
  669. // eslint-disable-next-line prefer-template
  670. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (0, _print.printExpectedConstructorName)('Expected constructor', expected) + ((0, _getType.isPrimitive)(received) || Object.getPrototypeOf(received) === null ? `\nReceived value has no prototype\nReceived value: ${(0, _jestMatcherUtils.printReceived)(received)}` : typeof received.constructor === 'function' ? (0, _print.printReceivedConstructorName)('Received constructor', received.constructor) : `\nReceived value: ${(0, _jestMatcherUtils.printReceived)(received)}`);
  671. return {
  672. message,
  673. pass
  674. };
  675. },
  676. toBeLessThan(received, expected) {
  677. const matcherName = 'toBeLessThan';
  678. const isNot = this.isNot;
  679. const options = {
  680. isNot,
  681. promise: this.promise
  682. };
  683. (0, _jestMatcherUtils.ensureNumbers)(received, expected, matcherName, options);
  684. const pass = received < expected;
  685. const message = () =>
  686. // eslint-disable-next-line prefer-template
  687. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected:${isNot ? ' not' : ''} < ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received:${isNot ? ' ' : ''} ${(0, _jestMatcherUtils.printReceived)(received)}`;
  688. return {
  689. message,
  690. pass
  691. };
  692. },
  693. toBeLessThanOrEqual(received, expected) {
  694. const matcherName = 'toBeLessThanOrEqual';
  695. const isNot = this.isNot;
  696. const options = {
  697. isNot,
  698. promise: this.promise
  699. };
  700. (0, _jestMatcherUtils.ensureNumbers)(received, expected, matcherName, options);
  701. const pass = received <= expected;
  702. const message = () =>
  703. // eslint-disable-next-line prefer-template
  704. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected:${isNot ? ' not' : ''} <= ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received:${isNot ? ' ' : ''} ${(0, _jestMatcherUtils.printReceived)(received)}`;
  705. return {
  706. message,
  707. pass
  708. };
  709. },
  710. toBeNaN(received, expected) {
  711. const matcherName = 'toBeNaN';
  712. const options = {
  713. isNot: this.isNot,
  714. promise: this.promise
  715. };
  716. (0, _jestMatcherUtils.ensureNoExpected)(expected, matcherName, options);
  717. const pass = Number.isNaN(received);
  718. const message = () =>
  719. // eslint-disable-next-line prefer-template
  720. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`;
  721. return {
  722. message,
  723. pass
  724. };
  725. },
  726. toBeNull(received, expected) {
  727. const matcherName = 'toBeNull';
  728. const options = {
  729. isNot: this.isNot,
  730. promise: this.promise
  731. };
  732. (0, _jestMatcherUtils.ensureNoExpected)(expected, matcherName, options);
  733. const pass = received === null;
  734. const message = () =>
  735. // eslint-disable-next-line prefer-template
  736. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`;
  737. return {
  738. message,
  739. pass
  740. };
  741. },
  742. toBeTruthy(received, expected) {
  743. const matcherName = 'toBeTruthy';
  744. const options = {
  745. isNot: this.isNot,
  746. promise: this.promise
  747. };
  748. (0, _jestMatcherUtils.ensureNoExpected)(expected, matcherName, options);
  749. const pass = !!received;
  750. const message = () =>
  751. // eslint-disable-next-line prefer-template
  752. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`;
  753. return {
  754. message,
  755. pass
  756. };
  757. },
  758. toBeUndefined(received, expected) {
  759. const matcherName = 'toBeUndefined';
  760. const options = {
  761. isNot: this.isNot,
  762. promise: this.promise
  763. };
  764. (0, _jestMatcherUtils.ensureNoExpected)(expected, matcherName, options);
  765. const pass = received === void 0;
  766. const message = () =>
  767. // eslint-disable-next-line prefer-template
  768. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`;
  769. return {
  770. message,
  771. pass
  772. };
  773. },
  774. toContain(received, expected) {
  775. const matcherName = 'toContain';
  776. const isNot = this.isNot;
  777. const options = {
  778. comment: 'indexOf',
  779. isNot,
  780. promise: this.promise
  781. };
  782. if (received == null) {
  783. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must not be null nor undefined`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  784. }
  785. if (typeof received === 'string') {
  786. const wrongTypeErrorMessage = `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} value must be a string if ${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value is a string`;
  787. if (typeof expected !== 'string') {
  788. throw new TypeError((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, received, String(expected), options), wrongTypeErrorMessage,
  789. // eslint-disable-next-line prefer-template
  790. (0, _jestMatcherUtils.printWithType)('Expected', expected, _jestMatcherUtils.printExpected) + '\n' + (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  791. }
  792. const index = received.indexOf(String(expected));
  793. const pass = index !== -1;
  794. const message = () => {
  795. const labelExpected = `Expected ${typeof expected === 'string' ? 'substring' : 'value'}`;
  796. const labelReceived = 'Received string';
  797. const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(labelExpected, labelReceived);
  798. return (
  799. // eslint-disable-next-line prefer-template
  800. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `${printLabel(labelExpected)}${isNot ? 'not ' : ''}${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `${printLabel(labelReceived)}${isNot ? ' ' : ''}${isNot ? (0, _print.printReceivedStringContainExpectedSubstring)(received, index, String(expected).length) : (0, _jestMatcherUtils.printReceived)(received)}`
  801. );
  802. };
  803. return {
  804. message,
  805. pass
  806. };
  807. }
  808. const indexable = [...received];
  809. const index = indexable.indexOf(expected);
  810. const pass = index !== -1;
  811. const message = () => {
  812. const labelExpected = 'Expected value';
  813. const labelReceived = `Received ${(0, _getType.getType)(received)}`;
  814. const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(labelExpected, labelReceived);
  815. return (
  816. // eslint-disable-next-line prefer-template
  817. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `${printLabel(labelExpected)}${isNot ? 'not ' : ''}${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `${printLabel(labelReceived)}${isNot ? ' ' : ''}${isNot && Array.isArray(received) ? (0, _print.printReceivedArrayContainExpectedItem)(received, index) : (0, _jestMatcherUtils.printReceived)(received)}` + (!isNot && indexable.some(item => (0, _expectUtils.equals)(item, expected, [...this.customTesters, _expectUtils.iterableEquality])) ? `\n\n${_jestMatcherUtils.SUGGEST_TO_CONTAIN_EQUAL}` : '')
  818. );
  819. };
  820. return {
  821. message,
  822. pass
  823. };
  824. },
  825. toContainEqual(received, expected) {
  826. const matcherName = 'toContainEqual';
  827. const isNot = this.isNot;
  828. const options = {
  829. comment: 'deep equality',
  830. isNot,
  831. promise: this.promise
  832. };
  833. if (received == null) {
  834. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must not be null nor undefined`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  835. }
  836. const index = [...received].findIndex(item => (0, _expectUtils.equals)(item, expected, [...this.customTesters, _expectUtils.iterableEquality]));
  837. const pass = index !== -1;
  838. const message = () => {
  839. const labelExpected = 'Expected value';
  840. const labelReceived = `Received ${(0, _getType.getType)(received)}`;
  841. const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(labelExpected, labelReceived);
  842. return (
  843. // eslint-disable-next-line prefer-template
  844. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `${printLabel(labelExpected)}${isNot ? 'not ' : ''}${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `${printLabel(labelReceived)}${isNot ? ' ' : ''}${isNot && Array.isArray(received) ? (0, _print.printReceivedArrayContainExpectedItem)(received, index) : (0, _jestMatcherUtils.printReceived)(received)}`
  845. );
  846. };
  847. return {
  848. message,
  849. pass
  850. };
  851. },
  852. toEqual(received, expected) {
  853. const matcherName = 'toEqual';
  854. const options = {
  855. comment: 'deep equality',
  856. isNot: this.isNot,
  857. promise: this.promise
  858. };
  859. const pass = (0, _expectUtils.equals)(received, expected, [...this.customTesters, _expectUtils.iterableEquality]);
  860. const message = pass ? () =>
  861. // eslint-disable-next-line prefer-template
  862. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + ((0, _jestMatcherUtils.stringify)(expected) === (0, _jestMatcherUtils.stringify)(received) ? '' : `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`) : () =>
  863. // eslint-disable-next-line prefer-template
  864. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (0, _jestMatcherUtils.printDiffOrStringify)(expected, received, EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand));
  865. // Passing the actual and expected objects so that a custom reporter
  866. // could access them, for example in order to display a custom visual diff,
  867. // or create a different error message
  868. return {
  869. actual: received,
  870. expected,
  871. message,
  872. name: matcherName,
  873. pass
  874. };
  875. },
  876. toHaveLength(received, expected) {
  877. const matcherName = 'toHaveLength';
  878. const isNot = this.isNot;
  879. const options = {
  880. isNot,
  881. promise: this.promise
  882. };
  883. if (typeof received?.length !== 'number') {
  884. throw new TypeError((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must have a length property whose value must be a number`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  885. }
  886. (0, _jestMatcherUtils.ensureExpectedIsNonNegativeInteger)(expected, matcherName, options);
  887. const pass = received.length === expected;
  888. const message = () => {
  889. const labelExpected = 'Expected length';
  890. const labelReceivedLength = 'Received length';
  891. const labelReceivedValue = `Received ${(0, _getType.getType)(received)}`;
  892. const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(labelExpected, labelReceivedLength, labelReceivedValue);
  893. return (
  894. // eslint-disable-next-line prefer-template
  895. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `${printLabel(labelExpected)}${isNot ? 'not ' : ''}${(0, _jestMatcherUtils.printExpected)(expected)}\n` + (isNot ? '' : `${printLabel(labelReceivedLength)}${(0, _jestMatcherUtils.printReceived)(received.length)}\n`) + `${printLabel(labelReceivedValue)}${isNot ? ' ' : ''}${(0, _jestMatcherUtils.printReceived)(received)}`
  896. );
  897. };
  898. return {
  899. message,
  900. pass
  901. };
  902. },
  903. toHaveProperty(received, expectedPath, expectedValue) {
  904. const matcherName = 'toHaveProperty';
  905. const expectedArgument = 'path';
  906. const hasValue = arguments.length === 3;
  907. const options = {
  908. isNot: this.isNot,
  909. promise: this.promise,
  910. secondArgument: hasValue ? 'value' : ''
  911. };
  912. if (received === null || received === undefined) {
  913. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, expectedArgument, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must not be null nor undefined`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  914. }
  915. const expectedPathType = (0, _getType.getType)(expectedPath);
  916. if (expectedPathType !== 'string' && expectedPathType !== 'array') {
  917. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, expectedArgument, options), `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} path must be a string or array`, (0, _jestMatcherUtils.printWithType)('Expected', expectedPath, _jestMatcherUtils.printExpected)));
  918. }
  919. const expectedPathLength = typeof expectedPath === 'string' ? (0, _expectUtils.pathAsArray)(expectedPath).length : expectedPath.length;
  920. if (expectedPathType === 'array' && expectedPathLength === 0) {
  921. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, expectedArgument, options), `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} path must not be an empty array`, (0, _jestMatcherUtils.printWithType)('Expected', expectedPath, _jestMatcherUtils.printExpected)));
  922. }
  923. const result = (0, _expectUtils.getPath)(received, expectedPath);
  924. const {
  925. lastTraversedObject,
  926. endPropIsDefined,
  927. hasEndProp,
  928. value
  929. } = result;
  930. const receivedPath = result.traversedPath;
  931. const hasCompletePath = receivedPath.length === expectedPathLength;
  932. const receivedValue = hasCompletePath ? result.value : lastTraversedObject;
  933. const pass = hasValue && endPropIsDefined ? (0, _expectUtils.equals)(value, expectedValue, [...this.customTesters, _expectUtils.iterableEquality]) : Boolean(hasEndProp);
  934. const message = pass ? () =>
  935. // eslint-disable-next-line prefer-template
  936. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, expectedArgument, options) + '\n\n' + (hasValue ? `Expected path: ${(0, _jestMatcherUtils.printExpected)(expectedPath)}\n\n` + `Expected value: not ${(0, _jestMatcherUtils.printExpected)(expectedValue)}${(0, _jestMatcherUtils.stringify)(expectedValue) === (0, _jestMatcherUtils.stringify)(receivedValue) ? '' : `\nReceived value: ${(0, _jestMatcherUtils.printReceived)(receivedValue)}`}` : `Expected path: not ${(0, _jestMatcherUtils.printExpected)(expectedPath)}\n\n` + `Received value: ${(0, _jestMatcherUtils.printReceived)(receivedValue)}`) : () =>
  937. // eslint-disable-next-line prefer-template
  938. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, expectedArgument, options) + '\n\n' + `Expected path: ${(0, _jestMatcherUtils.printExpected)(expectedPath)}\n` + (hasCompletePath ? `\n${(0, _jestMatcherUtils.printDiffOrStringify)(expectedValue, receivedValue, EXPECTED_VALUE_LABEL, RECEIVED_VALUE_LABEL, isExpand(this.expand))}` : `Received path: ${(0, _jestMatcherUtils.printReceived)(expectedPathType === 'array' || receivedPath.length === 0 ? receivedPath : receivedPath.join('.'))}\n\n${hasValue ? `Expected value: ${(0, _jestMatcherUtils.printExpected)(expectedValue)}\n` : ''}Received value: ${(0, _jestMatcherUtils.printReceived)(receivedValue)}`);
  939. return {
  940. message,
  941. pass
  942. };
  943. },
  944. toMatch(received, expected) {
  945. const matcherName = 'toMatch';
  946. const options = {
  947. isNot: this.isNot,
  948. promise: this.promise
  949. };
  950. if (typeof received !== 'string') {
  951. throw new TypeError((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must be a string`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  952. }
  953. if (!(typeof expected === 'string') && !(expected && typeof expected.test === 'function')) {
  954. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} value must be a string or regular expression`, (0, _jestMatcherUtils.printWithType)('Expected', expected, _jestMatcherUtils.printExpected)));
  955. }
  956. const pass = typeof expected === 'string' ? received.includes(expected) : new RegExp(expected).test(received);
  957. const message = pass ? () => typeof expected === 'string' ?
  958. // eslint-disable-next-line prefer-template
  959. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected substring: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received string: ${(0, _print.printReceivedStringContainExpectedSubstring)(received, received.indexOf(expected), expected.length)}` :
  960. // eslint-disable-next-line prefer-template
  961. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected pattern: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received string: ${(0, _print.printReceivedStringContainExpectedResult)(received, typeof expected.exec === 'function' ? expected.exec(received) : null)}` : () => {
  962. const labelExpected = `Expected ${typeof expected === 'string' ? 'substring' : 'pattern'}`;
  963. const labelReceived = 'Received string';
  964. const printLabel = (0, _jestMatcherUtils.getLabelPrinter)(labelExpected, labelReceived);
  965. return (
  966. // eslint-disable-next-line prefer-template
  967. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `${printLabel(labelExpected)}${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `${printLabel(labelReceived)}${(0, _jestMatcherUtils.printReceived)(received)}`
  968. );
  969. };
  970. return {
  971. message,
  972. pass
  973. };
  974. },
  975. toMatchObject(received, expected) {
  976. const matcherName = 'toMatchObject';
  977. const options = {
  978. isNot: this.isNot,
  979. promise: this.promise
  980. };
  981. if (typeof received !== 'object' || received === null) {
  982. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must be a non-null object`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  983. }
  984. if (typeof expected !== 'object' || expected === null) {
  985. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} value must be a non-null object`, (0, _jestMatcherUtils.printWithType)('Expected', expected, _jestMatcherUtils.printExpected)));
  986. }
  987. const pass = (0, _expectUtils.equals)(received, expected, [...this.customTesters, _expectUtils.iterableEquality, _expectUtils.subsetEquality]);
  988. const message = pass ? () =>
  989. // eslint-disable-next-line prefer-template
  990. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}` + ((0, _jestMatcherUtils.stringify)(expected) === (0, _jestMatcherUtils.stringify)(received) ? '' : `\nReceived: ${(0, _jestMatcherUtils.printReceived)(received)}`) : () =>
  991. // eslint-disable-next-line prefer-template
  992. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (0, _jestMatcherUtils.printDiffOrStringify)(expected, (0, _expectUtils.getObjectSubset)(received, expected, this.customTesters), EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand));
  993. return {
  994. message,
  995. pass
  996. };
  997. },
  998. toStrictEqual(received, expected) {
  999. const matcherName = 'toStrictEqual';
  1000. const options = {
  1001. comment: 'deep equality',
  1002. isNot: this.isNot,
  1003. promise: this.promise
  1004. };
  1005. const pass = (0, _expectUtils.equals)(received, expected, [...this.customTesters, ...toStrictEqualTesters], true);
  1006. const message = pass ? () =>
  1007. // eslint-disable-next-line prefer-template
  1008. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + ((0, _jestMatcherUtils.stringify)(expected) === (0, _jestMatcherUtils.stringify)(received) ? '' : `Received: ${(0, _jestMatcherUtils.printReceived)(received)}`) : () =>
  1009. // eslint-disable-next-line prefer-template
  1010. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (0, _jestMatcherUtils.printDiffOrStringify)(expected, received, EXPECTED_LABEL, RECEIVED_LABEL, isExpand(this.expand));
  1011. // Passing the actual and expected objects so that a custom reporter
  1012. // could access them, for example in order to display a custom visual diff,
  1013. // or create a different error message
  1014. return {
  1015. actual: received,
  1016. expected,
  1017. message,
  1018. name: matcherName,
  1019. pass
  1020. };
  1021. }
  1022. };
  1023. var _default = exports["default"] = matchers;
  1024. /***/ }),
  1025. /***/ "./src/print.ts":
  1026. /***/ ((__unused_webpack_module, exports) => {
  1027. Object.defineProperty(exports, "__esModule", ({
  1028. value: true
  1029. }));
  1030. exports.printReceivedStringContainExpectedSubstring = exports.printReceivedStringContainExpectedResult = exports.printReceivedConstructorNameNot = exports.printReceivedConstructorName = exports.printReceivedArrayContainExpectedItem = exports.printExpectedConstructorNameNot = exports.printExpectedConstructorName = exports.printCloseTo = void 0;
  1031. var _jestMatcherUtils = require("jest-matcher-utils");
  1032. /**
  1033. * Copyright (c) Meta Platforms, Inc. and affiliates.
  1034. *
  1035. * This source code is licensed under the MIT license found in the
  1036. * LICENSE file in the root directory of this source tree.
  1037. *
  1038. */
  1039. // Format substring but do not enclose in double quote marks.
  1040. // The replacement is compatible with pretty-format package.
  1041. const printSubstring = val => val.replaceAll(/"|\\/g, '\\$&');
  1042. const printReceivedStringContainExpectedSubstring = (received, start, length // not end
  1043. ) => (0, _jestMatcherUtils.RECEIVED_COLOR)(`"${printSubstring(received.slice(0, start))}${(0, _jestMatcherUtils.INVERTED_COLOR)(printSubstring(received.slice(start, start + length)))}${printSubstring(received.slice(start + length))}"`);
  1044. exports.printReceivedStringContainExpectedSubstring = printReceivedStringContainExpectedSubstring;
  1045. const printReceivedStringContainExpectedResult = (received, result) => result === null ? (0, _jestMatcherUtils.printReceived)(received) : printReceivedStringContainExpectedSubstring(received, result.index, result[0].length);
  1046. // The serialized array is compatible with pretty-format package min option.
  1047. // However, items have default stringify depth (instead of depth - 1)
  1048. // so expected item looks consistent by itself and enclosed in the array.
  1049. exports.printReceivedStringContainExpectedResult = printReceivedStringContainExpectedResult;
  1050. const printReceivedArrayContainExpectedItem = (received, index) => (0, _jestMatcherUtils.RECEIVED_COLOR)(`[${received.map((item, i) => {
  1051. const stringified = (0, _jestMatcherUtils.stringify)(item);
  1052. return i === index ? (0, _jestMatcherUtils.INVERTED_COLOR)(stringified) : stringified;
  1053. }).join(', ')}]`);
  1054. exports.printReceivedArrayContainExpectedItem = printReceivedArrayContainExpectedItem;
  1055. const printCloseTo = (receivedDiff, expectedDiff, precision, isNot) => {
  1056. const receivedDiffString = (0, _jestMatcherUtils.stringify)(receivedDiff);
  1057. const expectedDiffString = receivedDiffString.includes('e') ?
  1058. // toExponential arg is number of digits after the decimal point.
  1059. expectedDiff.toExponential(0) : 0 <= precision && precision < 20 ?
  1060. // toFixed arg is number of digits after the decimal point.
  1061. // It may be a value between 0 and 20 inclusive.
  1062. // Implementations may optionally support a larger range of values.
  1063. expectedDiff.toFixed(precision + 1) : (0, _jestMatcherUtils.stringify)(expectedDiff);
  1064. return `Expected precision: ${isNot ? ' ' : ''} ${(0, _jestMatcherUtils.stringify)(precision)}\n` + `Expected difference: ${isNot ? 'not ' : ''}< ${(0, _jestMatcherUtils.EXPECTED_COLOR)(expectedDiffString)}\n` + `Received difference: ${isNot ? ' ' : ''} ${(0, _jestMatcherUtils.RECEIVED_COLOR)(receivedDiffString)}`;
  1065. };
  1066. exports.printCloseTo = printCloseTo;
  1067. const printExpectedConstructorName = (label, expected) => `${printConstructorName(label, expected, false, true)}\n`;
  1068. exports.printExpectedConstructorName = printExpectedConstructorName;
  1069. const printExpectedConstructorNameNot = (label, expected) => `${printConstructorName(label, expected, true, true)}\n`;
  1070. exports.printExpectedConstructorNameNot = printExpectedConstructorNameNot;
  1071. const printReceivedConstructorName = (label, received) => `${printConstructorName(label, received, false, false)}\n`;
  1072. // Do not call function if received is equal to expected.
  1073. exports.printReceivedConstructorName = printReceivedConstructorName;
  1074. const printReceivedConstructorNameNot = (label, received, expected) => typeof expected.name === 'string' && expected.name.length > 0 && typeof received.name === 'string' && received.name.length > 0 ? `${printConstructorName(label, received, true, false)} ${Object.getPrototypeOf(received) === expected ? 'extends' : 'extends … extends'} ${(0, _jestMatcherUtils.EXPECTED_COLOR)(expected.name)}\n` : `${printConstructorName(label, received, false, false)}\n`;
  1075. exports.printReceivedConstructorNameNot = printReceivedConstructorNameNot;
  1076. const printConstructorName = (label, constructor, isNot, isExpected) => typeof constructor.name === 'string' ? constructor.name.length === 0 ? `${label} name is an empty string` : `${label}: ${isNot ? isExpected ? 'not ' : ' ' : ''}${isExpected ? (0, _jestMatcherUtils.EXPECTED_COLOR)(constructor.name) : (0, _jestMatcherUtils.RECEIVED_COLOR)(constructor.name)}` : `${label} name is not a string`;
  1077. /***/ }),
  1078. /***/ "./src/spyMatchers.ts":
  1079. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1080. Object.defineProperty(exports, "__esModule", ({
  1081. value: true
  1082. }));
  1083. exports["default"] = void 0;
  1084. var _expectUtils = require("@jest/expect-utils");
  1085. var _getType = require("@jest/get-type");
  1086. var _jestMatcherUtils = require("jest-matcher-utils");
  1087. var _jestMatchersObject = __webpack_require__("./src/jestMatchersObject.ts");
  1088. /**
  1089. * Copyright (c) Meta Platforms, Inc. and affiliates.
  1090. *
  1091. * This source code is licensed under the MIT license found in the
  1092. * LICENSE file in the root directory of this source tree.
  1093. */
  1094. /* eslint-disable unicorn/consistent-function-scoping */
  1095. // The optional property of matcher context is true if undefined.
  1096. const isExpand = expand => expand !== false;
  1097. const PRINT_LIMIT = 3;
  1098. const NO_ARGUMENTS = 'called with 0 arguments';
  1099. const printExpectedArgs = expected => expected.length === 0 ? NO_ARGUMENTS : expected.map(arg => (0, _jestMatcherUtils.printExpected)(arg)).join(', ');
  1100. const printReceivedArgs = (received, expected) => received.length === 0 ? NO_ARGUMENTS : received.map((arg, i) => Array.isArray(expected) && i < expected.length && isEqualValue(expected[i], arg) ? printCommon(arg) : (0, _jestMatcherUtils.printReceived)(arg)).join(', ');
  1101. const printCommon = val => (0, _jestMatcherUtils.DIM_COLOR)((0, _jestMatcherUtils.stringify)(val));
  1102. const isEqualValue = (expected, received) => (0, _expectUtils.equals)(expected, received, [...(0, _jestMatchersObject.getCustomEqualityTesters)(), _expectUtils.iterableEquality]);
  1103. const isEqualCall = (expected, received) => received.length === expected.length && isEqualValue(expected, received);
  1104. const isEqualReturn = (expected, result) => result.type === 'return' && isEqualValue(expected, result.value);
  1105. const countReturns = results => results.reduce((n, result) => result.type === 'return' ? n + 1 : n, 0);
  1106. const printNumberOfReturns = (countReturns, countCalls) => `\nNumber of returns: ${(0, _jestMatcherUtils.printReceived)(countReturns)}${countCalls === countReturns ? '' : `\nNumber of calls: ${(0, _jestMatcherUtils.printReceived)(countCalls)}`}`;
  1107. // Given a label, return a function which given a string,
  1108. // right-aligns it preceding the colon in the label.
  1109. const getRightAlignedPrinter = label => {
  1110. // Assume that the label contains a colon.
  1111. const index = label.indexOf(':');
  1112. const suffix = label.slice(index);
  1113. return (string, isExpectedCall) => (isExpectedCall ? `->${' '.repeat(Math.max(0, index - 2 - string.length))}` : ' '.repeat(Math.max(index - string.length))) + string + suffix;
  1114. };
  1115. const printReceivedCallsNegative = (expected, indexedCalls, isOnlyCall, iExpectedCall) => {
  1116. if (indexedCalls.length === 0) {
  1117. return '';
  1118. }
  1119. const label = 'Received: ';
  1120. if (isOnlyCall) {
  1121. return `${label + printReceivedArgs(indexedCalls[0], expected)}\n`;
  1122. }
  1123. const printAligned = getRightAlignedPrinter(label);
  1124. return `Received\n${indexedCalls.reduce((printed, [i, args]) => `${printed + printAligned(String(i + 1), i === iExpectedCall) + printReceivedArgs(args, expected)}\n`, '')}`;
  1125. };
  1126. const printExpectedReceivedCallsPositive = (expected, indexedCalls, expand, isOnlyCall, iExpectedCall) => {
  1127. const expectedLine = `Expected: ${printExpectedArgs(expected)}\n`;
  1128. if (indexedCalls.length === 0) {
  1129. return expectedLine;
  1130. }
  1131. const label = 'Received: ';
  1132. if (isOnlyCall && (iExpectedCall === 0 || iExpectedCall === undefined)) {
  1133. const received = indexedCalls[0][1];
  1134. if (isLineDiffableCall(expected, received)) {
  1135. // Display diff without indentation.
  1136. const lines = [(0, _jestMatcherUtils.EXPECTED_COLOR)('- Expected'), (0, _jestMatcherUtils.RECEIVED_COLOR)('+ Received'), ''];
  1137. const length = Math.max(expected.length, received.length);
  1138. for (let i = 0; i < length; i += 1) {
  1139. if (i < expected.length && i < received.length) {
  1140. if (isEqualValue(expected[i], received[i])) {
  1141. lines.push(` ${printCommon(received[i])},`);
  1142. continue;
  1143. }
  1144. if (isLineDiffableArg(expected[i], received[i])) {
  1145. const difference = (0, _jestMatcherUtils.diff)(expected[i], received[i], {
  1146. expand
  1147. });
  1148. if (typeof difference === 'string' && difference.includes('- Expected') && difference.includes('+ Received')) {
  1149. // Omit annotation in case multiple args have diff.
  1150. lines.push(`${difference.split('\n').slice(3).join('\n')},`);
  1151. continue;
  1152. }
  1153. }
  1154. }
  1155. if (i < expected.length) {
  1156. lines.push(`${(0, _jestMatcherUtils.EXPECTED_COLOR)(`- ${(0, _jestMatcherUtils.stringify)(expected[i])}`)},`);
  1157. }
  1158. if (i < received.length) {
  1159. lines.push(`${(0, _jestMatcherUtils.RECEIVED_COLOR)(`+ ${(0, _jestMatcherUtils.stringify)(received[i])}`)},`);
  1160. }
  1161. }
  1162. return `${lines.join('\n')}\n`;
  1163. }
  1164. return `${expectedLine + label + printReceivedArgs(received, expected)}\n`;
  1165. }
  1166. const printAligned = getRightAlignedPrinter(label);
  1167. return (
  1168. // eslint-disable-next-line prefer-template
  1169. expectedLine + 'Received\n' + indexedCalls.reduce((printed, [i, received]) => {
  1170. const aligned = printAligned(String(i + 1), i === iExpectedCall);
  1171. return `${printed + ((i === iExpectedCall || iExpectedCall === undefined) && isLineDiffableCall(expected, received) ? aligned.replace(': ', '\n') + printDiffCall(expected, received, expand) : aligned + printReceivedArgs(received, expected))}\n`;
  1172. }, '')
  1173. );
  1174. };
  1175. const indentation = 'Received'.replaceAll(/\w/g, ' ');
  1176. const printDiffCall = (expected, received, expand) => received.map((arg, i) => {
  1177. if (i < expected.length) {
  1178. if (isEqualValue(expected[i], arg)) {
  1179. return `${indentation} ${printCommon(arg)},`;
  1180. }
  1181. if (isLineDiffableArg(expected[i], arg)) {
  1182. const difference = (0, _jestMatcherUtils.diff)(expected[i], arg, {
  1183. expand
  1184. });
  1185. if (typeof difference === 'string' && difference.includes('- Expected') && difference.includes('+ Received')) {
  1186. // Display diff with indentation.
  1187. // Omit annotation in case multiple args have diff.
  1188. return `${difference.split('\n').slice(3).map(line => indentation + line).join('\n')},`;
  1189. }
  1190. }
  1191. }
  1192. // Display + only if received arg has no corresponding expected arg.
  1193. return `${indentation + (i < expected.length ? ` ${(0, _jestMatcherUtils.printReceived)(arg)}` : (0, _jestMatcherUtils.RECEIVED_COLOR)(`+ ${(0, _jestMatcherUtils.stringify)(arg)}`))},`;
  1194. }).join('\n');
  1195. const isLineDiffableCall = (expected, received) => expected.some((arg, i) => i < received.length && isLineDiffableArg(arg, received[i]));
  1196. // Almost redundant with function in jest-matcher-utils,
  1197. // except no line diff for any strings.
  1198. const isLineDiffableArg = (expected, received) => {
  1199. const expectedType = (0, _getType.getType)(expected);
  1200. const receivedType = (0, _getType.getType)(received);
  1201. if (expectedType !== receivedType) {
  1202. return false;
  1203. }
  1204. if ((0, _getType.isPrimitive)(expected)) {
  1205. return false;
  1206. }
  1207. if (expectedType === 'date' || expectedType === 'function' || expectedType === 'regexp') {
  1208. return false;
  1209. }
  1210. if (expected instanceof Error && received instanceof Error) {
  1211. return false;
  1212. }
  1213. if (expectedType === 'object' && typeof expected.asymmetricMatch === 'function') {
  1214. return false;
  1215. }
  1216. if (receivedType === 'object' && typeof received.asymmetricMatch === 'function') {
  1217. return false;
  1218. }
  1219. return true;
  1220. };
  1221. const printResult = (result, expected) => result.type === 'throw' ? 'function call threw an error' : result.type === 'incomplete' ? 'function call has not returned yet' : isEqualValue(expected, result.value) ? printCommon(result.value) : (0, _jestMatcherUtils.printReceived)(result.value);
  1222. // Return either empty string or one line per indexed result,
  1223. // so additional empty line can separate from `Number of returns` which follows.
  1224. const printReceivedResults = (label, expected, indexedResults, isOnlyCall, iExpectedCall) => {
  1225. if (indexedResults.length === 0) {
  1226. return '';
  1227. }
  1228. if (isOnlyCall && (iExpectedCall === 0 || iExpectedCall === undefined)) {
  1229. return `${label + printResult(indexedResults[0][1], expected)}\n`;
  1230. }
  1231. const printAligned = getRightAlignedPrinter(label);
  1232. return (
  1233. // eslint-disable-next-line prefer-template
  1234. label.replace(':', '').trim() + '\n' + indexedResults.reduce((printed, [i, result]) => `${printed + printAligned(String(i + 1), i === iExpectedCall) + printResult(result, expected)}\n`, '')
  1235. );
  1236. };
  1237. const createToHaveBeenCalledMatcher = () => function (received, expected) {
  1238. const expectedArgument = '';
  1239. const options = {
  1240. isNot: this.isNot,
  1241. promise: this.promise
  1242. };
  1243. (0, _jestMatcherUtils.ensureNoExpected)(expected, 'toHaveBeenCalled', options);
  1244. ensureMockOrSpy(received, 'toHaveBeenCalled', expectedArgument, options);
  1245. const receivedIsSpy = isSpy(received);
  1246. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  1247. const count = receivedIsSpy ? received.calls.count() : received.mock.calls.length;
  1248. const calls = receivedIsSpy ? received.calls.all().map(x => x.args) : received.mock.calls;
  1249. const pass = count > 0;
  1250. const message = pass ? () =>
  1251. // eslint-disable-next-line prefer-template
  1252. (0, _jestMatcherUtils.matcherHint)('toHaveBeenCalled', receivedName, expectedArgument, options) + '\n\n' + `Expected number of calls: ${(0, _jestMatcherUtils.printExpected)(0)}\n` + `Received number of calls: ${(0, _jestMatcherUtils.printReceived)(count)}\n\n` + calls.reduce((lines, args, i) => {
  1253. if (lines.length < PRINT_LIMIT) {
  1254. lines.push(`${i + 1}: ${printReceivedArgs(args)}`);
  1255. }
  1256. return lines;
  1257. }, []).join('\n') : () =>
  1258. // eslint-disable-next-line prefer-template
  1259. (0, _jestMatcherUtils.matcherHint)('toHaveBeenCalled', receivedName, expectedArgument, options) + '\n\n' + `Expected number of calls: >= ${(0, _jestMatcherUtils.printExpected)(1)}\n` + `Received number of calls: ${(0, _jestMatcherUtils.printReceived)(count)}`;
  1260. return {
  1261. message,
  1262. pass
  1263. };
  1264. };
  1265. const createToHaveReturnedMatcher = () => function (received, expected) {
  1266. const expectedArgument = '';
  1267. const options = {
  1268. isNot: this.isNot,
  1269. promise: this.promise
  1270. };
  1271. (0, _jestMatcherUtils.ensureNoExpected)(expected, 'toHaveReturned', options);
  1272. ensureMock(received, 'toHaveReturned', expectedArgument, options);
  1273. const receivedName = received.getMockName();
  1274. // Count return values that correspond only to calls that returned
  1275. const count = received.mock.results.reduce((n, result) => result.type === 'return' ? n + 1 : n, 0);
  1276. const pass = count > 0;
  1277. const message = pass ? () =>
  1278. // eslint-disable-next-line prefer-template
  1279. (0, _jestMatcherUtils.matcherHint)('toHaveReturned', receivedName, expectedArgument, options) + '\n\n' + `Expected number of returns: ${(0, _jestMatcherUtils.printExpected)(0)}\n` + `Received number of returns: ${(0, _jestMatcherUtils.printReceived)(count)}\n\n` + received.mock.results.reduce((lines, result, i) => {
  1280. if (result.type === 'return' && lines.length < PRINT_LIMIT) {
  1281. lines.push(`${i + 1}: ${(0, _jestMatcherUtils.printReceived)(result.value)}`);
  1282. }
  1283. return lines;
  1284. }, []).join('\n') + (received.mock.calls.length === count ? '' : `\n\nReceived number of calls: ${(0, _jestMatcherUtils.printReceived)(received.mock.calls.length)}`) : () =>
  1285. // eslint-disable-next-line prefer-template
  1286. (0, _jestMatcherUtils.matcherHint)('toHaveReturned', receivedName, expectedArgument, options) + '\n\n' + `Expected number of returns: >= ${(0, _jestMatcherUtils.printExpected)(1)}\n` + `Received number of returns: ${(0, _jestMatcherUtils.printReceived)(count)}` + (received.mock.calls.length === count ? '' : `\nReceived number of calls: ${(0, _jestMatcherUtils.printReceived)(received.mock.calls.length)}`);
  1287. return {
  1288. message,
  1289. pass
  1290. };
  1291. };
  1292. const createToHaveBeenCalledTimesMatcher = () => function (received, expected) {
  1293. const expectedArgument = 'expected';
  1294. const options = {
  1295. isNot: this.isNot,
  1296. promise: this.promise
  1297. };
  1298. (0, _jestMatcherUtils.ensureExpectedIsNonNegativeInteger)(expected, 'toHaveBeenCalledTimes', options);
  1299. ensureMockOrSpy(received, 'toHaveBeenCalledTimes', expectedArgument, options);
  1300. const receivedIsSpy = isSpy(received);
  1301. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  1302. const count = receivedIsSpy ? received.calls.count() : received.mock.calls.length;
  1303. const pass = count === expected;
  1304. const message = pass ? () =>
  1305. // eslint-disable-next-line prefer-template
  1306. (0, _jestMatcherUtils.matcherHint)('toHaveBeenCalledTimes', receivedName, expectedArgument, options) + '\n\n' + `Expected number of calls: not ${(0, _jestMatcherUtils.printExpected)(expected)}` : () =>
  1307. // eslint-disable-next-line prefer-template
  1308. (0, _jestMatcherUtils.matcherHint)('toHaveBeenCalledTimes', receivedName, expectedArgument, options) + '\n\n' + `Expected number of calls: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received number of calls: ${(0, _jestMatcherUtils.printReceived)(count)}`;
  1309. return {
  1310. message,
  1311. pass
  1312. };
  1313. };
  1314. const createToHaveReturnedTimesMatcher = () => function (received, expected) {
  1315. const expectedArgument = 'expected';
  1316. const options = {
  1317. isNot: this.isNot,
  1318. promise: this.promise
  1319. };
  1320. (0, _jestMatcherUtils.ensureExpectedIsNonNegativeInteger)(expected, 'toHaveReturnedTimes', options);
  1321. ensureMock(received, 'toHaveReturnedTimes', expectedArgument, options);
  1322. const receivedName = received.getMockName();
  1323. // Count return values that correspond only to calls that returned
  1324. const count = received.mock.results.reduce((n, result) => result.type === 'return' ? n + 1 : n, 0);
  1325. const pass = count === expected;
  1326. const message = pass ? () =>
  1327. // eslint-disable-next-line prefer-template
  1328. (0, _jestMatcherUtils.matcherHint)('toHaveReturnedTimes', receivedName, expectedArgument, options) + '\n\n' + `Expected number of returns: not ${(0, _jestMatcherUtils.printExpected)(expected)}` + (received.mock.calls.length === count ? '' : `\n\nReceived number of calls: ${(0, _jestMatcherUtils.printReceived)(received.mock.calls.length)}`) : () =>
  1329. // eslint-disable-next-line prefer-template
  1330. (0, _jestMatcherUtils.matcherHint)('toHaveReturnedTimes', receivedName, expectedArgument, options) + '\n\n' + `Expected number of returns: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + `Received number of returns: ${(0, _jestMatcherUtils.printReceived)(count)}` + (received.mock.calls.length === count ? '' : `\nReceived number of calls: ${(0, _jestMatcherUtils.printReceived)(received.mock.calls.length)}`);
  1331. return {
  1332. message,
  1333. pass
  1334. };
  1335. };
  1336. const createToHaveBeenCalledWithMatcher = () => function (received, ...expected) {
  1337. const expectedArgument = '...expected';
  1338. const options = {
  1339. isNot: this.isNot,
  1340. promise: this.promise
  1341. };
  1342. ensureMockOrSpy(received, 'toHaveBeenCalledWith', expectedArgument, options);
  1343. const receivedIsSpy = isSpy(received);
  1344. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  1345. const calls = receivedIsSpy ? received.calls.all().map(x => x.args) : received.mock.calls;
  1346. const pass = calls.some(call => isEqualCall(expected, call));
  1347. const message = pass ? () => {
  1348. // Some examples of calls that are equal to expected value.
  1349. const indexedCalls = [];
  1350. let i = 0;
  1351. while (i < calls.length && indexedCalls.length < PRINT_LIMIT) {
  1352. if (isEqualCall(expected, calls[i])) {
  1353. indexedCalls.push([i, calls[i]]);
  1354. }
  1355. i += 1;
  1356. }
  1357. return (
  1358. // eslint-disable-next-line prefer-template
  1359. (0, _jestMatcherUtils.matcherHint)('toHaveBeenCalledWith', receivedName, expectedArgument, options) + '\n\n' + `Expected: not ${printExpectedArgs(expected)}\n` + (calls.length === 1 && (0, _jestMatcherUtils.stringify)(calls[0]) === (0, _jestMatcherUtils.stringify)(expected) ? '' : printReceivedCallsNegative(expected, indexedCalls, calls.length === 1)) + `\nNumber of calls: ${(0, _jestMatcherUtils.printReceived)(calls.length)}`
  1360. );
  1361. } : () => {
  1362. // Some examples of calls that are not equal to expected value.
  1363. const indexedCalls = [];
  1364. let i = 0;
  1365. while (i < calls.length && indexedCalls.length < PRINT_LIMIT) {
  1366. indexedCalls.push([i, calls[i]]);
  1367. i += 1;
  1368. }
  1369. return (
  1370. // eslint-disable-next-line prefer-template
  1371. (0, _jestMatcherUtils.matcherHint)('toHaveBeenCalledWith', receivedName, expectedArgument, options) + '\n\n' + printExpectedReceivedCallsPositive(expected, indexedCalls, isExpand(this.expand), calls.length === 1) + `\nNumber of calls: ${(0, _jestMatcherUtils.printReceived)(calls.length)}`
  1372. );
  1373. };
  1374. return {
  1375. message,
  1376. pass
  1377. };
  1378. };
  1379. const createToHaveReturnedWithMatcher = () => function (received, expected) {
  1380. const expectedArgument = 'expected';
  1381. const options = {
  1382. isNot: this.isNot,
  1383. promise: this.promise
  1384. };
  1385. ensureMock(received, 'toHaveReturnedWith', expectedArgument, options);
  1386. const receivedName = received.getMockName();
  1387. const {
  1388. calls,
  1389. results
  1390. } = received.mock;
  1391. const pass = results.some(result => isEqualReturn(expected, result));
  1392. const message = pass ? () => {
  1393. // Some examples of results that are equal to expected value.
  1394. const indexedResults = [];
  1395. let i = 0;
  1396. while (i < results.length && indexedResults.length < PRINT_LIMIT) {
  1397. if (isEqualReturn(expected, results[i])) {
  1398. indexedResults.push([i, results[i]]);
  1399. }
  1400. i += 1;
  1401. }
  1402. return (
  1403. // eslint-disable-next-line prefer-template
  1404. (0, _jestMatcherUtils.matcherHint)('toHaveReturnedWith', receivedName, expectedArgument, options) + '\n\n' + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + (results.length === 1 && results[0].type === 'return' && (0, _jestMatcherUtils.stringify)(results[0].value) === (0, _jestMatcherUtils.stringify)(expected) ? '' : printReceivedResults('Received: ', expected, indexedResults, results.length === 1)) + printNumberOfReturns(countReturns(results), calls.length)
  1405. );
  1406. } : () => {
  1407. // Some examples of results that are not equal to expected value.
  1408. const indexedResults = [];
  1409. let i = 0;
  1410. while (i < results.length && indexedResults.length < PRINT_LIMIT) {
  1411. indexedResults.push([i, results[i]]);
  1412. i += 1;
  1413. }
  1414. return (
  1415. // eslint-disable-next-line prefer-template
  1416. (0, _jestMatcherUtils.matcherHint)('toHaveReturnedWith', receivedName, expectedArgument, options) + '\n\n' + `Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + printReceivedResults('Received: ', expected, indexedResults, results.length === 1) + printNumberOfReturns(countReturns(results), calls.length)
  1417. );
  1418. };
  1419. return {
  1420. message,
  1421. pass
  1422. };
  1423. };
  1424. const createToHaveBeenLastCalledWithMatcher = () => function (received, ...expected) {
  1425. const expectedArgument = '...expected';
  1426. const options = {
  1427. isNot: this.isNot,
  1428. promise: this.promise
  1429. };
  1430. ensureMockOrSpy(received, 'toHaveBeenLastCalledWith', expectedArgument, options);
  1431. const receivedIsSpy = isSpy(received);
  1432. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  1433. const calls = receivedIsSpy ? received.calls.all().map(x => x.args) : received.mock.calls;
  1434. const iLast = calls.length - 1;
  1435. const pass = iLast >= 0 && isEqualCall(expected, calls[iLast]);
  1436. const message = pass ? () => {
  1437. const indexedCalls = [];
  1438. if (iLast > 0) {
  1439. // Display preceding call as context.
  1440. indexedCalls.push([iLast - 1, calls[iLast - 1]]);
  1441. }
  1442. indexedCalls.push([iLast, calls[iLast]]);
  1443. return (
  1444. // eslint-disable-next-line prefer-template
  1445. (0, _jestMatcherUtils.matcherHint)('toHaveBeenLastCalledWith', receivedName, expectedArgument, options) + '\n\n' + `Expected: not ${printExpectedArgs(expected)}\n` + (calls.length === 1 && (0, _jestMatcherUtils.stringify)(calls[0]) === (0, _jestMatcherUtils.stringify)(expected) ? '' : printReceivedCallsNegative(expected, indexedCalls, calls.length === 1, iLast)) + `\nNumber of calls: ${(0, _jestMatcherUtils.printReceived)(calls.length)}`
  1446. );
  1447. } : () => {
  1448. const indexedCalls = [];
  1449. if (iLast >= 0) {
  1450. if (iLast > 0) {
  1451. let i = iLast - 1;
  1452. // Is there a preceding call that is equal to expected args?
  1453. while (i >= 0 && !isEqualCall(expected, calls[i])) {
  1454. i -= 1;
  1455. }
  1456. if (i < 0) {
  1457. i = iLast - 1; // otherwise, preceding call
  1458. }
  1459. indexedCalls.push([i, calls[i]]);
  1460. }
  1461. indexedCalls.push([iLast, calls[iLast]]);
  1462. }
  1463. return (
  1464. // eslint-disable-next-line prefer-template
  1465. (0, _jestMatcherUtils.matcherHint)('toHaveBeenLastCalledWith', receivedName, expectedArgument, options) + '\n\n' + printExpectedReceivedCallsPositive(expected, indexedCalls, isExpand(this.expand), calls.length === 1, iLast) + `\nNumber of calls: ${(0, _jestMatcherUtils.printReceived)(calls.length)}`
  1466. );
  1467. };
  1468. return {
  1469. message,
  1470. pass
  1471. };
  1472. };
  1473. const createToHaveLastReturnedWithMatcher = () => function (received, expected) {
  1474. const expectedArgument = 'expected';
  1475. const options = {
  1476. isNot: this.isNot,
  1477. promise: this.promise
  1478. };
  1479. ensureMock(received, 'toHaveLastReturnedWith', expectedArgument, options);
  1480. const receivedName = received.getMockName();
  1481. const {
  1482. calls,
  1483. results
  1484. } = received.mock;
  1485. const iLast = results.length - 1;
  1486. const pass = iLast >= 0 && isEqualReturn(expected, results[iLast]);
  1487. const message = pass ? () => {
  1488. const indexedResults = [];
  1489. if (iLast > 0) {
  1490. // Display preceding result as context.
  1491. indexedResults.push([iLast - 1, results[iLast - 1]]);
  1492. }
  1493. indexedResults.push([iLast, results[iLast]]);
  1494. return (
  1495. // eslint-disable-next-line prefer-template
  1496. (0, _jestMatcherUtils.matcherHint)('toHaveLastReturnedWith', receivedName, expectedArgument, options) + '\n\n' + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + (results.length === 1 && results[0].type === 'return' && (0, _jestMatcherUtils.stringify)(results[0].value) === (0, _jestMatcherUtils.stringify)(expected) ? '' : printReceivedResults('Received: ', expected, indexedResults, results.length === 1, iLast)) + printNumberOfReturns(countReturns(results), calls.length)
  1497. );
  1498. } : () => {
  1499. const indexedResults = [];
  1500. if (iLast >= 0) {
  1501. if (iLast > 0) {
  1502. let i = iLast - 1;
  1503. // Is there a preceding result that is equal to expected value?
  1504. while (i >= 0 && !isEqualReturn(expected, results[i])) {
  1505. i -= 1;
  1506. }
  1507. if (i < 0) {
  1508. i = iLast - 1; // otherwise, preceding result
  1509. }
  1510. indexedResults.push([i, results[i]]);
  1511. }
  1512. indexedResults.push([iLast, results[iLast]]);
  1513. }
  1514. return (
  1515. // eslint-disable-next-line prefer-template
  1516. (0, _jestMatcherUtils.matcherHint)('toHaveLastReturnedWith', receivedName, expectedArgument, options) + '\n\n' + `Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + printReceivedResults('Received: ', expected, indexedResults, results.length === 1, iLast) + printNumberOfReturns(countReturns(results), calls.length)
  1517. );
  1518. };
  1519. return {
  1520. message,
  1521. pass
  1522. };
  1523. };
  1524. const createToHaveBeenNthCalledWithMatcher = () => function (received, nth, ...expected) {
  1525. const expectedArgument = 'n';
  1526. const options = {
  1527. expectedColor: arg => arg,
  1528. isNot: this.isNot,
  1529. promise: this.promise,
  1530. secondArgument: '...expected'
  1531. };
  1532. ensureMockOrSpy(received, 'toHaveBeenNthCalledWith', expectedArgument, options);
  1533. if (!Number.isSafeInteger(nth) || nth < 1) {
  1534. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)('toHaveBeenNthCalledWith', undefined, expectedArgument, options), `${expectedArgument} must be a positive integer`, (0, _jestMatcherUtils.printWithType)(expectedArgument, nth, _jestMatcherUtils.stringify)));
  1535. }
  1536. const receivedIsSpy = isSpy(received);
  1537. const receivedName = receivedIsSpy ? 'spy' : received.getMockName();
  1538. const calls = receivedIsSpy ? received.calls.all().map(x => x.args) : received.mock.calls;
  1539. const length = calls.length;
  1540. const iNth = nth - 1;
  1541. const pass = iNth < length && isEqualCall(expected, calls[iNth]);
  1542. const message = pass ? () => {
  1543. // Display preceding and following calls,
  1544. // in case assertions fails because index is off by one.
  1545. const indexedCalls = [];
  1546. if (iNth - 1 >= 0) {
  1547. indexedCalls.push([iNth - 1, calls[iNth - 1]]);
  1548. }
  1549. indexedCalls.push([iNth, calls[iNth]]);
  1550. if (iNth + 1 < length) {
  1551. indexedCalls.push([iNth + 1, calls[iNth + 1]]);
  1552. }
  1553. return (
  1554. // eslint-disable-next-line prefer-template
  1555. (0, _jestMatcherUtils.matcherHint)('toHaveBeenNthCalledWith', receivedName, expectedArgument, options) + '\n\n' + `n: ${nth}\n` + `Expected: not ${printExpectedArgs(expected)}\n` + (calls.length === 1 && (0, _jestMatcherUtils.stringify)(calls[0]) === (0, _jestMatcherUtils.stringify)(expected) ? '' : printReceivedCallsNegative(expected, indexedCalls, calls.length === 1, iNth)) + `\nNumber of calls: ${(0, _jestMatcherUtils.printReceived)(calls.length)}`
  1556. );
  1557. } : () => {
  1558. // Display preceding and following calls:
  1559. // * nearest call that is equal to expected args
  1560. // * otherwise, adjacent call
  1561. // in case assertions fails because of index, especially off by one.
  1562. const indexedCalls = [];
  1563. if (iNth < length) {
  1564. if (iNth - 1 >= 0) {
  1565. let i = iNth - 1;
  1566. // Is there a preceding call that is equal to expected args?
  1567. while (i >= 0 && !isEqualCall(expected, calls[i])) {
  1568. i -= 1;
  1569. }
  1570. if (i < 0) {
  1571. i = iNth - 1; // otherwise, adjacent call
  1572. }
  1573. indexedCalls.push([i, calls[i]]);
  1574. }
  1575. indexedCalls.push([iNth, calls[iNth]]);
  1576. if (iNth + 1 < length) {
  1577. let i = iNth + 1;
  1578. // Is there a following call that is equal to expected args?
  1579. while (i < length && !isEqualCall(expected, calls[i])) {
  1580. i += 1;
  1581. }
  1582. if (i >= length) {
  1583. i = iNth + 1; // otherwise, adjacent call
  1584. }
  1585. indexedCalls.push([i, calls[i]]);
  1586. }
  1587. } else if (length > 0) {
  1588. // The number of received calls is fewer than the expected number.
  1589. let i = length - 1;
  1590. // Is there a call that is equal to expected args?
  1591. while (i >= 0 && !isEqualCall(expected, calls[i])) {
  1592. i -= 1;
  1593. }
  1594. if (i < 0) {
  1595. i = length - 1; // otherwise, last call
  1596. }
  1597. indexedCalls.push([i, calls[i]]);
  1598. }
  1599. return (
  1600. // eslint-disable-next-line prefer-template
  1601. (0, _jestMatcherUtils.matcherHint)('toHaveBeenNthCalledWith', receivedName, expectedArgument, options) + '\n\n' + `n: ${nth}\n` + printExpectedReceivedCallsPositive(expected, indexedCalls, isExpand(this.expand), calls.length === 1, iNth) + `\nNumber of calls: ${(0, _jestMatcherUtils.printReceived)(calls.length)}`
  1602. );
  1603. };
  1604. return {
  1605. message,
  1606. pass
  1607. };
  1608. };
  1609. const createToHaveNthReturnedWithMatcher = () => function (received, nth, expected) {
  1610. const expectedArgument = 'n';
  1611. const options = {
  1612. expectedColor: arg => arg,
  1613. isNot: this.isNot,
  1614. promise: this.promise,
  1615. secondArgument: 'expected'
  1616. };
  1617. ensureMock(received, 'toHaveNthReturnedWith', expectedArgument, options);
  1618. if (!Number.isSafeInteger(nth) || nth < 1) {
  1619. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)('toHaveNthReturnedWith', undefined, expectedArgument, options), `${expectedArgument} must be a positive integer`, (0, _jestMatcherUtils.printWithType)(expectedArgument, nth, _jestMatcherUtils.stringify)));
  1620. }
  1621. const receivedName = received.getMockName();
  1622. const {
  1623. calls,
  1624. results
  1625. } = received.mock;
  1626. const length = results.length;
  1627. const iNth = nth - 1;
  1628. const pass = iNth < length && isEqualReturn(expected, results[iNth]);
  1629. const message = pass ? () => {
  1630. // Display preceding and following results,
  1631. // in case assertions fails because index is off by one.
  1632. const indexedResults = [];
  1633. if (iNth - 1 >= 0) {
  1634. indexedResults.push([iNth - 1, results[iNth - 1]]);
  1635. }
  1636. indexedResults.push([iNth, results[iNth]]);
  1637. if (iNth + 1 < length) {
  1638. indexedResults.push([iNth + 1, results[iNth + 1]]);
  1639. }
  1640. return (
  1641. // eslint-disable-next-line prefer-template
  1642. (0, _jestMatcherUtils.matcherHint)('toHaveNthReturnedWith', receivedName, expectedArgument, options) + '\n\n' + `n: ${nth}\n` + `Expected: not ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + (results.length === 1 && results[0].type === 'return' && (0, _jestMatcherUtils.stringify)(results[0].value) === (0, _jestMatcherUtils.stringify)(expected) ? '' : printReceivedResults('Received: ', expected, indexedResults, results.length === 1, iNth)) + printNumberOfReturns(countReturns(results), calls.length)
  1643. );
  1644. } : () => {
  1645. // Display preceding and following results:
  1646. // * nearest result that is equal to expected value
  1647. // * otherwise, adjacent result
  1648. // in case assertions fails because of index, especially off by one.
  1649. const indexedResults = [];
  1650. if (iNth < length) {
  1651. if (iNth - 1 >= 0) {
  1652. let i = iNth - 1;
  1653. // Is there a preceding result that is equal to expected value?
  1654. while (i >= 0 && !isEqualReturn(expected, results[i])) {
  1655. i -= 1;
  1656. }
  1657. if (i < 0) {
  1658. i = iNth - 1; // otherwise, adjacent result
  1659. }
  1660. indexedResults.push([i, results[i]]);
  1661. }
  1662. indexedResults.push([iNth, results[iNth]]);
  1663. if (iNth + 1 < length) {
  1664. let i = iNth + 1;
  1665. // Is there a following result that is equal to expected value?
  1666. while (i < length && !isEqualReturn(expected, results[i])) {
  1667. i += 1;
  1668. }
  1669. if (i >= length) {
  1670. i = iNth + 1; // otherwise, adjacent result
  1671. }
  1672. indexedResults.push([i, results[i]]);
  1673. }
  1674. } else if (length > 0) {
  1675. // The number of received calls is fewer than the expected number.
  1676. let i = length - 1;
  1677. // Is there a result that is equal to expected value?
  1678. while (i >= 0 && !isEqualReturn(expected, results[i])) {
  1679. i -= 1;
  1680. }
  1681. if (i < 0) {
  1682. i = length - 1; // otherwise, last result
  1683. }
  1684. indexedResults.push([i, results[i]]);
  1685. }
  1686. return (
  1687. // eslint-disable-next-line prefer-template
  1688. (0, _jestMatcherUtils.matcherHint)('toHaveNthReturnedWith', receivedName, expectedArgument, options) + '\n\n' + `n: ${nth}\n` + `Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + printReceivedResults('Received: ', expected, indexedResults, results.length === 1, iNth) + printNumberOfReturns(countReturns(results), calls.length)
  1689. );
  1690. };
  1691. return {
  1692. message,
  1693. pass
  1694. };
  1695. };
  1696. const spyMatchers = {
  1697. toHaveBeenCalled: createToHaveBeenCalledMatcher(),
  1698. toHaveBeenCalledTimes: createToHaveBeenCalledTimesMatcher(),
  1699. toHaveBeenCalledWith: createToHaveBeenCalledWithMatcher(),
  1700. toHaveBeenLastCalledWith: createToHaveBeenLastCalledWithMatcher(),
  1701. toHaveBeenNthCalledWith: createToHaveBeenNthCalledWithMatcher(),
  1702. toHaveLastReturnedWith: createToHaveLastReturnedWithMatcher(),
  1703. toHaveNthReturnedWith: createToHaveNthReturnedWithMatcher(),
  1704. toHaveReturned: createToHaveReturnedMatcher(),
  1705. toHaveReturnedTimes: createToHaveReturnedTimesMatcher(),
  1706. toHaveReturnedWith: createToHaveReturnedWithMatcher()
  1707. };
  1708. const isMock = received => received != null && received._isMockFunction === true;
  1709. const isSpy = received => received != null && received.calls != null && typeof received.calls.all === 'function' && typeof received.calls.count === 'function';
  1710. const ensureMockOrSpy = (received, matcherName, expectedArgument, options) => {
  1711. if (!isMock(received) && !isSpy(received)) {
  1712. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, expectedArgument, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must be a mock or spy function`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  1713. }
  1714. };
  1715. const ensureMock = (received, matcherName, expectedArgument, options) => {
  1716. if (!isMock(received)) {
  1717. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, expectedArgument, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must be a mock function`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  1718. }
  1719. };
  1720. var _default = exports["default"] = spyMatchers;
  1721. /***/ }),
  1722. /***/ "./src/toThrowMatchers.ts":
  1723. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1724. Object.defineProperty(exports, "__esModule", ({
  1725. value: true
  1726. }));
  1727. exports["default"] = exports.createMatcher = void 0;
  1728. var _expectUtils = require("@jest/expect-utils");
  1729. var _jestMatcherUtils = require("jest-matcher-utils");
  1730. var _jestMessageUtil = require("jest-message-util");
  1731. var _print = __webpack_require__("./src/print.ts");
  1732. /**
  1733. * Copyright (c) Meta Platforms, Inc. and affiliates.
  1734. *
  1735. * This source code is licensed under the MIT license found in the
  1736. * LICENSE file in the root directory of this source tree.
  1737. *
  1738. */
  1739. const DID_NOT_THROW = 'Received function did not throw';
  1740. const getThrown = e => {
  1741. const hasMessage = e !== null && e !== undefined && typeof e.message === 'string';
  1742. if (hasMessage && typeof e.name === 'string' && typeof e.stack === 'string') {
  1743. return {
  1744. hasMessage,
  1745. isError: true,
  1746. message: e.message,
  1747. value: e
  1748. };
  1749. }
  1750. return {
  1751. hasMessage,
  1752. isError: false,
  1753. message: hasMessage ? e.message : String(e),
  1754. value: e
  1755. };
  1756. };
  1757. const createMatcher = (matcherName, fromPromise) => function (received, expected) {
  1758. const options = {
  1759. isNot: this.isNot,
  1760. promise: this.promise
  1761. };
  1762. let thrown = null;
  1763. if (fromPromise && (0, _expectUtils.isError)(received)) {
  1764. thrown = getThrown(received);
  1765. } else {
  1766. if (typeof received === 'function') {
  1767. try {
  1768. received();
  1769. } catch (error) {
  1770. thrown = getThrown(error);
  1771. }
  1772. } else {
  1773. if (!fromPromise) {
  1774. const placeholder = expected === undefined ? '' : 'expected';
  1775. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, placeholder, options), `${(0, _jestMatcherUtils.RECEIVED_COLOR)('received')} value must be a function`, (0, _jestMatcherUtils.printWithType)('Received', received, _jestMatcherUtils.printReceived)));
  1776. }
  1777. }
  1778. }
  1779. if (expected === undefined) {
  1780. return toThrow(matcherName, options, thrown);
  1781. } else if (typeof expected === 'function') {
  1782. return toThrowExpectedClass(matcherName, options, thrown, expected);
  1783. } else if (typeof expected === 'string') {
  1784. return toThrowExpectedString(matcherName, options, thrown, expected);
  1785. } else if (expected !== null && typeof expected.test === 'function') {
  1786. return toThrowExpectedRegExp(matcherName, options, thrown, expected);
  1787. } else if (expected !== null && typeof expected.asymmetricMatch === 'function') {
  1788. return toThrowExpectedAsymmetric(matcherName, options, thrown, expected);
  1789. } else if (expected !== null && typeof expected === 'object') {
  1790. return toThrowExpectedObject(matcherName, options, thrown, expected);
  1791. } else {
  1792. throw new Error((0, _jestMatcherUtils.matcherErrorMessage)((0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options), `${(0, _jestMatcherUtils.EXPECTED_COLOR)('expected')} value must be a string or regular expression or class or error`, (0, _jestMatcherUtils.printWithType)('Expected', expected, _jestMatcherUtils.printExpected)));
  1793. }
  1794. };
  1795. exports.createMatcher = createMatcher;
  1796. const matchers = {
  1797. toThrow: createMatcher('toThrow')
  1798. };
  1799. const toThrowExpectedRegExp = (matcherName, options, thrown, expected) => {
  1800. const pass = thrown !== null && expected.test(thrown.message);
  1801. const message = pass ? () =>
  1802. // eslint-disable-next-line prefer-template
  1803. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + formatExpected('Expected pattern: not ', expected) + (thrown !== null && thrown.hasMessage ? formatReceived('Received message: ', thrown, 'message', expected) + formatStack(thrown) : formatReceived('Received value: ', thrown, 'value')) : () =>
  1804. // eslint-disable-next-line prefer-template
  1805. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + formatExpected('Expected pattern: ', expected) + (thrown === null ? `\n${DID_NOT_THROW}` : thrown.hasMessage ? formatReceived('Received message: ', thrown, 'message') + formatStack(thrown) : formatReceived('Received value: ', thrown, 'value'));
  1806. return {
  1807. message,
  1808. pass
  1809. };
  1810. };
  1811. const toThrowExpectedAsymmetric = (matcherName, options, thrown, expected) => {
  1812. const pass = thrown !== null && expected.asymmetricMatch(thrown.value);
  1813. const message = pass ? () =>
  1814. // eslint-disable-next-line prefer-template
  1815. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + formatExpected('Expected asymmetric matcher: not ', expected) + '\n' + (thrown !== null && thrown.hasMessage ? formatReceived('Received name: ', thrown, 'name') + formatReceived('Received message: ', thrown, 'message') + formatStack(thrown) : formatReceived('Thrown value: ', thrown, 'value')) : () =>
  1816. // eslint-disable-next-line prefer-template
  1817. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + formatExpected('Expected asymmetric matcher: ', expected) + '\n' + (thrown === null ? DID_NOT_THROW : thrown.hasMessage ? formatReceived('Received name: ', thrown, 'name') + formatReceived('Received message: ', thrown, 'message') + formatStack(thrown) : formatReceived('Thrown value: ', thrown, 'value'));
  1818. return {
  1819. message,
  1820. pass
  1821. };
  1822. };
  1823. const toThrowExpectedObject = (matcherName, options, thrown, expected) => {
  1824. const expectedMessageAndCause = createMessageAndCause(expected);
  1825. const thrownMessageAndCause = thrown === null ? null : createMessageAndCause(thrown.value);
  1826. const isCompareErrorInstance = thrown?.isError && expected instanceof Error;
  1827. const isExpectedCustomErrorInstance = expected.constructor.name !== Error.name;
  1828. const pass = thrown !== null && thrown.message === expected.message && thrownMessageAndCause === expectedMessageAndCause && (!isCompareErrorInstance || !isExpectedCustomErrorInstance || thrown.value instanceof expected.constructor);
  1829. const message = pass ? () =>
  1830. // eslint-disable-next-line prefer-template
  1831. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + formatExpected(`Expected ${messageAndCause(expected)}: not `, expectedMessageAndCause) + (thrown !== null && thrown.hasMessage ? formatStack(thrown) : formatReceived('Received value: ', thrown, 'value')) : () =>
  1832. // eslint-disable-next-line prefer-template
  1833. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (thrown === null ?
  1834. // eslint-disable-next-line prefer-template
  1835. formatExpected(`Expected ${messageAndCause(expected)}: `, expectedMessageAndCause) + '\n' + DID_NOT_THROW : thrown.hasMessage ?
  1836. // eslint-disable-next-line prefer-template
  1837. (0, _jestMatcherUtils.printDiffOrStringify)(expectedMessageAndCause, thrownMessageAndCause, `Expected ${messageAndCause(expected)}`, `Received ${messageAndCause(thrown.value)}`, true) + '\n' + formatStack(thrown) : formatExpected(`Expected ${messageAndCause(expected)}: `, expectedMessageAndCause) + formatReceived('Received value: ', thrown, 'value'));
  1838. return {
  1839. message,
  1840. pass
  1841. };
  1842. };
  1843. const toThrowExpectedClass = (matcherName, options, thrown, expected) => {
  1844. const pass = thrown !== null && thrown.value instanceof expected;
  1845. const message = pass ? () =>
  1846. // eslint-disable-next-line prefer-template
  1847. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (0, _print.printExpectedConstructorNameNot)('Expected constructor', expected) + (thrown !== null && thrown.value != null && typeof thrown.value.constructor === 'function' && thrown.value.constructor !== expected ? (0, _print.printReceivedConstructorNameNot)('Received constructor', thrown.value.constructor, expected) : '') + '\n' + (thrown !== null && thrown.hasMessage ? formatReceived('Received message: ', thrown, 'message') + formatStack(thrown) : formatReceived('Received value: ', thrown, 'value')) : () =>
  1848. // eslint-disable-next-line prefer-template
  1849. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + (0, _print.printExpectedConstructorName)('Expected constructor', expected) + (thrown === null ? `\n${DID_NOT_THROW}` : `${thrown.value != null && typeof thrown.value.constructor === 'function' ? (0, _print.printReceivedConstructorName)('Received constructor', thrown.value.constructor) : ''}\n${thrown.hasMessage ? formatReceived('Received message: ', thrown, 'message') + formatStack(thrown) : formatReceived('Received value: ', thrown, 'value')}`);
  1850. return {
  1851. message,
  1852. pass
  1853. };
  1854. };
  1855. const toThrowExpectedString = (matcherName, options, thrown, expected) => {
  1856. const pass = thrown !== null && thrown.message.includes(expected);
  1857. const message = pass ? () =>
  1858. // eslint-disable-next-line prefer-template
  1859. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + formatExpected('Expected substring: not ', expected) + (thrown !== null && thrown.hasMessage ? formatReceived('Received message: ', thrown, 'message', expected) + formatStack(thrown) : formatReceived('Received value: ', thrown, 'value')) : () =>
  1860. // eslint-disable-next-line prefer-template
  1861. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, undefined, options) + '\n\n' + formatExpected('Expected substring: ', expected) + (thrown === null ? `\n${DID_NOT_THROW}` : thrown.hasMessage ? formatReceived('Received message: ', thrown, 'message') + formatStack(thrown) : formatReceived('Received value: ', thrown, 'value'));
  1862. return {
  1863. message,
  1864. pass
  1865. };
  1866. };
  1867. const toThrow = (matcherName, options, thrown) => {
  1868. const pass = thrown !== null;
  1869. const message = pass ? () =>
  1870. // eslint-disable-next-line prefer-template
  1871. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + (thrown !== null && thrown.hasMessage ? formatReceived('Error name: ', thrown, 'name') + formatReceived('Error message: ', thrown, 'message') + formatStack(thrown) : formatReceived('Thrown value: ', thrown, 'value')) : () =>
  1872. // eslint-disable-next-line prefer-template
  1873. (0, _jestMatcherUtils.matcherHint)(matcherName, undefined, '', options) + '\n\n' + DID_NOT_THROW;
  1874. return {
  1875. message,
  1876. pass
  1877. };
  1878. };
  1879. const formatExpected = (label, expected) => `${label + (0, _jestMatcherUtils.printExpected)(expected)}\n`;
  1880. const formatReceived = (label, thrown, key, expected) => {
  1881. if (thrown === null) {
  1882. return '';
  1883. }
  1884. if (key === 'message') {
  1885. const message = thrown.message;
  1886. if (typeof expected === 'string') {
  1887. const index = message.indexOf(expected);
  1888. if (index !== -1) {
  1889. return `${label + (0, _print.printReceivedStringContainExpectedSubstring)(message, index, expected.length)}\n`;
  1890. }
  1891. } else if (expected instanceof RegExp) {
  1892. return `${label + (0, _print.printReceivedStringContainExpectedResult)(message, typeof expected.exec === 'function' ? expected.exec(message) : null)}\n`;
  1893. }
  1894. return `${label + (0, _jestMatcherUtils.printReceived)(message)}\n`;
  1895. }
  1896. if (key === 'name') {
  1897. return thrown.isError ? `${label + (0, _jestMatcherUtils.printReceived)(thrown.value.name)}\n` : '';
  1898. }
  1899. if (key === 'value') {
  1900. return thrown.isError ? '' : `${label + (0, _jestMatcherUtils.printReceived)(thrown.value)}\n`;
  1901. }
  1902. return '';
  1903. };
  1904. const formatStack = thrown => {
  1905. if (thrown === null || !thrown.isError) {
  1906. return '';
  1907. } else {
  1908. const config = {
  1909. rootDir: process.cwd(),
  1910. testMatch: []
  1911. };
  1912. const options = {
  1913. noStackTrace: false
  1914. };
  1915. if (thrown.value instanceof AggregateError) {
  1916. return (0, _jestMessageUtil.formatExecError)(thrown.value, config, options);
  1917. } else {
  1918. return (0, _jestMessageUtil.formatStackTrace)((0, _jestMessageUtil.separateMessageFromStack)(thrown.value.stack).stack, config, options);
  1919. }
  1920. }
  1921. };
  1922. function createMessageAndCause(error) {
  1923. if (error.cause) {
  1924. const seen = new WeakSet();
  1925. return JSON.stringify(buildSerializeError(error), (_, value) => {
  1926. if (isObject(value)) {
  1927. if (seen.has(value)) return;
  1928. seen.add(value); // stop circular references
  1929. }
  1930. if (typeof value === 'bigint' || value === undefined) {
  1931. return String(value);
  1932. }
  1933. return value;
  1934. });
  1935. }
  1936. return error.message;
  1937. }
  1938. function buildSerializeError(error) {
  1939. if (!isObject(error)) {
  1940. return error;
  1941. }
  1942. const result = {};
  1943. for (const name of Object.getOwnPropertyNames(error).sort()) {
  1944. if (['stack', 'fileName', 'lineNumber'].includes(name)) {
  1945. continue;
  1946. }
  1947. if (name === 'cause') {
  1948. result[name] = buildSerializeError(error['cause']);
  1949. continue;
  1950. }
  1951. result[name] = error[name];
  1952. }
  1953. return result;
  1954. }
  1955. function isObject(obj) {
  1956. return obj != null && typeof obj === 'object';
  1957. }
  1958. function messageAndCause(error) {
  1959. return error.cause === undefined ? 'message' : 'message and cause';
  1960. }
  1961. var _default = exports["default"] = matchers;
  1962. /***/ })
  1963. /******/ });
  1964. /************************************************************************/
  1965. /******/ // The module cache
  1966. /******/ var __webpack_module_cache__ = {};
  1967. /******/
  1968. /******/ // The require function
  1969. /******/ function __webpack_require__(moduleId) {
  1970. /******/ // Check if module is in cache
  1971. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  1972. /******/ if (cachedModule !== undefined) {
  1973. /******/ return cachedModule.exports;
  1974. /******/ }
  1975. /******/ // Create a new module (and put it into the cache)
  1976. /******/ var module = __webpack_module_cache__[moduleId] = {
  1977. /******/ // no module.id needed
  1978. /******/ // no module.loaded needed
  1979. /******/ exports: {}
  1980. /******/ };
  1981. /******/
  1982. /******/ // Execute the module function
  1983. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  1984. /******/
  1985. /******/ // Return the exports of the module
  1986. /******/ return module.exports;
  1987. /******/ }
  1988. /******/
  1989. /************************************************************************/
  1990. var __webpack_exports__ = {};
  1991. // This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
  1992. (() => {
  1993. var exports = __webpack_exports__;
  1994. Object.defineProperty(exports, "__esModule", ({
  1995. value: true
  1996. }));
  1997. Object.defineProperty(exports, "AsymmetricMatcher", ({
  1998. enumerable: true,
  1999. get: function () {
  2000. return _asymmetricMatchers.AsymmetricMatcher;
  2001. }
  2002. }));
  2003. exports.expect = exports["default"] = exports.JestAssertionError = void 0;
  2004. var _expectUtils = require("@jest/expect-utils");
  2005. var matcherUtils = _interopRequireWildcard(require("jest-matcher-utils"));
  2006. var _jestUtil = require("jest-util");
  2007. var _asymmetricMatchers = __webpack_require__("./src/asymmetricMatchers.ts");
  2008. var _extractExpectedAssertionsErrors = _interopRequireDefault(__webpack_require__("./src/extractExpectedAssertionsErrors.ts"));
  2009. var _jestMatchersObject = __webpack_require__("./src/jestMatchersObject.ts");
  2010. var _matchers = _interopRequireDefault(__webpack_require__("./src/matchers.ts"));
  2011. var _spyMatchers = _interopRequireDefault(__webpack_require__("./src/spyMatchers.ts"));
  2012. var _toThrowMatchers = _interopRequireWildcard(__webpack_require__("./src/toThrowMatchers.ts"));
  2013. function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
  2014. function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
  2015. /**
  2016. * Copyright (c) Meta Platforms, Inc. and affiliates.
  2017. *
  2018. * This source code is licensed under the MIT license found in the
  2019. * LICENSE file in the root directory of this source tree.
  2020. *
  2021. */
  2022. /* eslint-disable local/prefer-spread-eventually */
  2023. class JestAssertionError extends Error {
  2024. matcherResult;
  2025. }
  2026. exports.JestAssertionError = JestAssertionError;
  2027. const createToThrowErrorMatchingSnapshotMatcher = function (matcher) {
  2028. return function (received, testNameOrInlineSnapshot) {
  2029. return matcher.apply(this, [received, testNameOrInlineSnapshot, true]);
  2030. };
  2031. };
  2032. const getPromiseMatcher = (name, matcher) => {
  2033. if (name === 'toThrow') {
  2034. return (0, _toThrowMatchers.createMatcher)(name, true);
  2035. } else if (name === 'toThrowErrorMatchingSnapshot' || name === 'toThrowErrorMatchingInlineSnapshot') {
  2036. return createToThrowErrorMatchingSnapshotMatcher(matcher);
  2037. }
  2038. return null;
  2039. };
  2040. const expect = (actual, ...rest) => {
  2041. if (rest.length > 0) {
  2042. throw new Error('Expect takes at most one argument.');
  2043. }
  2044. const allMatchers = (0, _jestMatchersObject.getMatchers)();
  2045. const expectation = {
  2046. not: {},
  2047. rejects: {
  2048. not: {}
  2049. },
  2050. resolves: {
  2051. not: {}
  2052. }
  2053. };
  2054. const err = new JestAssertionError();
  2055. for (const name of Object.keys(allMatchers)) {
  2056. const matcher = allMatchers[name];
  2057. const promiseMatcher = getPromiseMatcher(name, matcher) || matcher;
  2058. expectation[name] = makeThrowingMatcher(matcher, false, '', actual);
  2059. expectation.not[name] = makeThrowingMatcher(matcher, true, '', actual);
  2060. expectation.resolves[name] = makeResolveMatcher(name, promiseMatcher, false, actual, err);
  2061. expectation.resolves.not[name] = makeResolveMatcher(name, promiseMatcher, true, actual, err);
  2062. expectation.rejects[name] = makeRejectMatcher(name, promiseMatcher, false, actual, err);
  2063. expectation.rejects.not[name] = makeRejectMatcher(name, promiseMatcher, true, actual, err);
  2064. }
  2065. return expectation;
  2066. };
  2067. exports.expect = expect;
  2068. const getMessage = message => message && message() || matcherUtils.RECEIVED_COLOR('No message was specified for this matcher.');
  2069. const makeResolveMatcher = (matcherName, matcher, isNot, actual, outerErr) => (...args) => {
  2070. const options = {
  2071. isNot,
  2072. promise: 'resolves'
  2073. };
  2074. const actualWrapper = typeof actual === 'function' ? actual() : actual;
  2075. if (!(0, _jestUtil.isPromise)(actualWrapper)) {
  2076. throw new JestAssertionError(matcherUtils.matcherErrorMessage(matcherUtils.matcherHint(matcherName, undefined, '', options), `${matcherUtils.RECEIVED_COLOR('received')} value must be a promise or a function returning a promise`, matcherUtils.printWithType('Received', actual, matcherUtils.printReceived)));
  2077. }
  2078. const innerErr = new JestAssertionError();
  2079. return actualWrapper.then(result => makeThrowingMatcher(matcher, isNot, 'resolves', result, innerErr).apply(null, args), error => {
  2080. outerErr.message = `${matcherUtils.matcherHint(matcherName, undefined, '', options)}\n\n` + 'Received promise rejected instead of resolved\n' + `Rejected to value: ${matcherUtils.printReceived(error)}`;
  2081. throw outerErr;
  2082. });
  2083. };
  2084. const makeRejectMatcher = (matcherName, matcher, isNot, actual, outerErr) => (...args) => {
  2085. const options = {
  2086. isNot,
  2087. promise: 'rejects'
  2088. };
  2089. const actualWrapper = typeof actual === 'function' ? actual() : actual;
  2090. if (!(0, _jestUtil.isPromise)(actualWrapper)) {
  2091. throw new JestAssertionError(matcherUtils.matcherErrorMessage(matcherUtils.matcherHint(matcherName, undefined, '', options), `${matcherUtils.RECEIVED_COLOR('received')} value must be a promise or a function returning a promise`, matcherUtils.printWithType('Received', actual, matcherUtils.printReceived)));
  2092. }
  2093. const innerErr = new JestAssertionError();
  2094. return actualWrapper.then(result => {
  2095. outerErr.message = `${matcherUtils.matcherHint(matcherName, undefined, '', options)}\n\n` + 'Received promise resolved instead of rejected\n' + `Resolved to value: ${matcherUtils.printReceived(result)}`;
  2096. throw outerErr;
  2097. }, error => makeThrowingMatcher(matcher, isNot, 'rejects', error, innerErr).apply(null, args));
  2098. };
  2099. const makeThrowingMatcher = (matcher, isNot, promise, actual, err) => function throwingMatcher(...args) {
  2100. let throws = true;
  2101. const utils = {
  2102. ...matcherUtils,
  2103. iterableEquality: _expectUtils.iterableEquality,
  2104. subsetEquality: _expectUtils.subsetEquality
  2105. };
  2106. const matcherUtilsThing = {
  2107. customTesters: (0, _jestMatchersObject.getCustomEqualityTesters)(),
  2108. // When throws is disabled, the matcher will not throw errors during test
  2109. // execution but instead add them to the global matcher state. If a
  2110. // matcher throws, test execution is normally stopped immediately. The
  2111. // snapshot matcher uses it because we want to log all snapshot
  2112. // failures in a test.
  2113. dontThrow: () => throws = false,
  2114. equals: _expectUtils.equals,
  2115. utils
  2116. };
  2117. const matcherContext = {
  2118. ...(0, _jestMatchersObject.getState)(),
  2119. ...matcherUtilsThing,
  2120. error: err,
  2121. isNot,
  2122. promise
  2123. };
  2124. const processResult = (result, asyncError) => {
  2125. _validateResult(result);
  2126. (0, _jestMatchersObject.getState)().assertionCalls++;
  2127. if (result.pass && isNot || !result.pass && !isNot) {
  2128. // XOR
  2129. const message = getMessage(result.message);
  2130. let error;
  2131. if (err) {
  2132. error = err;
  2133. error.message = message;
  2134. } else if (asyncError) {
  2135. error = asyncError;
  2136. error.message = message;
  2137. } else {
  2138. error = new JestAssertionError(message);
  2139. // Try to remove this function from the stack trace frame.
  2140. // Guard for some environments (browsers) that do not support this feature.
  2141. if (Error.captureStackTrace) {
  2142. Error.captureStackTrace(error, throwingMatcher);
  2143. }
  2144. }
  2145. // Passing the result of the matcher with the error so that a custom
  2146. // reporter could access the actual and expected objects of the result
  2147. // for example in order to display a custom visual diff
  2148. error.matcherResult = {
  2149. ...result,
  2150. message
  2151. };
  2152. if (throws) {
  2153. throw error;
  2154. } else {
  2155. (0, _jestMatchersObject.getState)().suppressedErrors.push(error);
  2156. }
  2157. } else {
  2158. (0, _jestMatchersObject.getState)().numPassingAsserts++;
  2159. }
  2160. };
  2161. const handleError = error => {
  2162. if (matcher[_jestMatchersObject.INTERNAL_MATCHER_FLAG] === true && !(error instanceof JestAssertionError) && error.name !== 'PrettyFormatPluginError' &&
  2163. // Guard for some environments (browsers) that do not support this feature.
  2164. Error.captureStackTrace) {
  2165. // Try to remove this and deeper functions from the stack trace frame.
  2166. Error.captureStackTrace(error, throwingMatcher);
  2167. }
  2168. throw error;
  2169. };
  2170. let potentialResult;
  2171. try {
  2172. potentialResult = matcher[_jestMatchersObject.INTERNAL_MATCHER_FLAG] === true ? matcher.call(matcherContext, actual, ...args) :
  2173. // It's a trap specifically for inline snapshot to capture this name
  2174. // in the stack trace, so that it can correctly get the custom matcher
  2175. // function call.
  2176. function __EXTERNAL_MATCHER_TRAP__() {
  2177. return matcher.call(matcherContext, actual, ...args);
  2178. }();
  2179. if ((0, _jestUtil.isPromise)(potentialResult)) {
  2180. const asyncError = new JestAssertionError();
  2181. if (Error.captureStackTrace) {
  2182. Error.captureStackTrace(asyncError, throwingMatcher);
  2183. }
  2184. return potentialResult.then(aResult => processResult(aResult, asyncError)).catch(handleError);
  2185. } else {
  2186. return processResult(potentialResult);
  2187. }
  2188. } catch (error) {
  2189. return handleError(error);
  2190. }
  2191. };
  2192. expect.extend = matchers => (0, _jestMatchersObject.setMatchers)(matchers, false, expect);
  2193. expect.addEqualityTesters = customTesters => (0, _jestMatchersObject.addCustomEqualityTesters)(customTesters);
  2194. expect.anything = _asymmetricMatchers.anything;
  2195. expect.any = _asymmetricMatchers.any;
  2196. expect.not = {
  2197. arrayContaining: _asymmetricMatchers.arrayNotContaining,
  2198. arrayOf: _asymmetricMatchers.notArrayOf,
  2199. closeTo: _asymmetricMatchers.notCloseTo,
  2200. objectContaining: _asymmetricMatchers.objectNotContaining,
  2201. stringContaining: _asymmetricMatchers.stringNotContaining,
  2202. stringMatching: _asymmetricMatchers.stringNotMatching
  2203. };
  2204. expect.arrayContaining = _asymmetricMatchers.arrayContaining;
  2205. expect.arrayOf = _asymmetricMatchers.arrayOf;
  2206. expect.closeTo = _asymmetricMatchers.closeTo;
  2207. expect.objectContaining = _asymmetricMatchers.objectContaining;
  2208. expect.stringContaining = _asymmetricMatchers.stringContaining;
  2209. expect.stringMatching = _asymmetricMatchers.stringMatching;
  2210. const _validateResult = result => {
  2211. if (typeof result !== 'object' || typeof result.pass !== 'boolean' || result.message && typeof result.message !== 'string' && typeof result.message !== 'function') {
  2212. throw new Error('Unexpected return from a matcher function.\n' + 'Matcher functions should ' + 'return an object in the following format:\n' + ' {message?: string | function, pass: boolean}\n' + `'${matcherUtils.stringify(result)}' was returned`);
  2213. }
  2214. };
  2215. function assertions(expected) {
  2216. const error = new _jestUtil.ErrorWithStack(undefined, assertions);
  2217. (0, _jestMatchersObject.setState)({
  2218. expectedAssertionsNumber: expected,
  2219. expectedAssertionsNumberError: error
  2220. });
  2221. }
  2222. function hasAssertions(...args) {
  2223. const error = new _jestUtil.ErrorWithStack(undefined, hasAssertions);
  2224. matcherUtils.ensureNoExpected(args[0], '.hasAssertions');
  2225. (0, _jestMatchersObject.setState)({
  2226. isExpectingAssertions: true,
  2227. isExpectingAssertionsError: error
  2228. });
  2229. }
  2230. // add default jest matchers
  2231. (0, _jestMatchersObject.setMatchers)(_matchers.default, true, expect);
  2232. (0, _jestMatchersObject.setMatchers)(_spyMatchers.default, true, expect);
  2233. (0, _jestMatchersObject.setMatchers)(_toThrowMatchers.default, true, expect);
  2234. expect.assertions = assertions;
  2235. expect.hasAssertions = hasAssertions;
  2236. expect.getState = _jestMatchersObject.getState;
  2237. expect.setState = _jestMatchersObject.setState;
  2238. expect.extractExpectedAssertionsErrors = _extractExpectedAssertionsErrors.default;
  2239. var _default = exports["default"] = expect;
  2240. })();
  2241. module.exports = __webpack_exports__;
  2242. /******/ })()
  2243. ;