test-common.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. var describe;
  2. var test;
  3. var expect;
  4. var withinSameSecond;
  5. // Stores the results of each test and suite. Has a terrible
  6. // name to avoid name collision.
  7. var __TestResults__ = {};
  8. // So test names like "toString" don't automatically produce an error
  9. Object.setPrototypeOf(__TestResults__, null);
  10. // This array is used to communicate with the C++ program. It treats
  11. // each message in this array as a separate message. Has a terrible
  12. // name to avoid name collision.
  13. var __UserOutput__ = [];
  14. // We also rebind console.log here to use the array above
  15. console.log = (...args) => {
  16. __UserOutput__.push(args.join(" "));
  17. };
  18. class ExpectationError extends Error {
  19. constructor(message) {
  20. super(message);
  21. this.name = "ExpectationError";
  22. }
  23. }
  24. // Use an IIFE to avoid polluting the global namespace as much as possible
  25. (() => {
  26. // FIXME: This is a very naive deepEquals algorithm
  27. const deepEquals = (a, b) => {
  28. if (Array.isArray(a)) return Array.isArray(b) && deepArrayEquals(a, b);
  29. if (typeof a === "object") return typeof b === "object" && deepObjectEquals(a, b);
  30. return Object.is(a, b);
  31. };
  32. const deepArrayEquals = (a, b) => {
  33. if (a.length !== b.length) return false;
  34. for (let i = 0; i < a.length; ++i) {
  35. if (!deepEquals(a[i], b[i])) return false;
  36. }
  37. return true;
  38. };
  39. const deepObjectEquals = (a, b) => {
  40. if (a === null) return b === null;
  41. for (let key of Reflect.ownKeys(a)) {
  42. if (!deepEquals(a[key], b[key])) return false;
  43. }
  44. return true;
  45. };
  46. const valueToString = value => {
  47. try {
  48. if (value === 0 && 1 / value < 0) {
  49. return "-0";
  50. }
  51. return String(value);
  52. } catch {
  53. // e.g for objects without a prototype, the above throws.
  54. return Object.prototype.toString.call(value);
  55. }
  56. };
  57. class Expector {
  58. constructor(target, inverted) {
  59. this.target = target;
  60. this.inverted = !!inverted;
  61. }
  62. get not() {
  63. return new Expector(this.target, !this.inverted);
  64. }
  65. toBe(value) {
  66. this.__doMatcher(() => {
  67. this.__expect(
  68. Object.is(this.target, value),
  69. () =>
  70. `toBe: expected _${valueToString(value)}_, got _${valueToString(
  71. this.target
  72. )}_`
  73. );
  74. });
  75. }
  76. // FIXME: Take a precision argument like jest's toBeCloseTo matcher
  77. toBeCloseTo(value) {
  78. this.__expect(
  79. typeof this.target === "number",
  80. () => `toBeCloseTo: expected target of type number, got ${typeof value}`
  81. );
  82. this.__expect(
  83. typeof value === "number",
  84. () => `toBeCloseTo: expected argument of type number, got ${typeof value}`
  85. );
  86. this.__doMatcher(() => {
  87. this.__expect(Math.abs(this.target - value) < 0.000001);
  88. });
  89. }
  90. toHaveLength(length) {
  91. this.__expect(
  92. typeof this.target.length === "number",
  93. () => "toHaveLength: target.length not of type number"
  94. );
  95. this.__doMatcher(() => {
  96. this.__expect(Object.is(this.target.length, length));
  97. });
  98. }
  99. toHaveSize(size) {
  100. this.__expect(
  101. typeof this.target.size === "number",
  102. () => "toHaveSize: target.size not of type number"
  103. );
  104. this.__doMatcher(() => {
  105. this.__expect(Object.is(this.target.size, size));
  106. });
  107. }
  108. toHaveProperty(property, value) {
  109. this.__doMatcher(() => {
  110. let object = this.target;
  111. if (typeof property === "string" && property.includes(".")) {
  112. let propertyArray = [];
  113. while (property.includes(".")) {
  114. let index = property.indexOf(".");
  115. propertyArray.push(property.substring(0, index));
  116. if (index + 1 >= property.length) break;
  117. property = property.substring(index + 1, property.length);
  118. }
  119. propertyArray.push(property);
  120. property = propertyArray;
  121. }
  122. if (Array.isArray(property)) {
  123. for (let key of property) {
  124. this.__expect(object !== undefined && object !== null);
  125. object = object[key];
  126. }
  127. } else {
  128. object = object[property];
  129. }
  130. this.__expect(object !== undefined);
  131. if (value !== undefined) this.__expect(deepEquals(object, value));
  132. });
  133. }
  134. toBeDefined() {
  135. this.__doMatcher(() => {
  136. this.__expect(
  137. this.target !== undefined,
  138. () => "toBeDefined: expected target to be defined, got undefined"
  139. );
  140. });
  141. }
  142. toBeInstanceOf(class_) {
  143. this.__doMatcher(() => {
  144. this.__expect(this.target instanceof class_);
  145. });
  146. }
  147. toBeNull() {
  148. this.__doMatcher(() => {
  149. this.__expect(this.target === null);
  150. });
  151. }
  152. toBeUndefined() {
  153. this.__doMatcher(() => {
  154. this.__expect(
  155. this.target === undefined,
  156. () =>
  157. `toBeUndefined: expected target to be undefined, got _${valueToString(
  158. this.target
  159. )}_`
  160. );
  161. });
  162. }
  163. toBeNaN() {
  164. this.__doMatcher(() => {
  165. this.__expect(
  166. isNaN(this.target),
  167. () => `toBeNaN: expected target to be NaN, got _${valueToString(this.target)}_`
  168. );
  169. });
  170. }
  171. toBeTrue() {
  172. this.__doMatcher(() => {
  173. this.__expect(
  174. this.target === true,
  175. () =>
  176. `toBeTrue: expected target to be true, got _${valueToString(this.target)}_`
  177. );
  178. });
  179. }
  180. toBeFalse() {
  181. this.__doMatcher(() => {
  182. this.__expect(
  183. this.target === false,
  184. () =>
  185. `toBeFalse: expected target to be false, got _${valueToString(
  186. this.target
  187. )}_`
  188. );
  189. });
  190. }
  191. __validateNumericComparisonTypes(value) {
  192. this.__expect(typeof this.target === "number" || typeof this.target === "bigint");
  193. this.__expect(typeof value === "number" || typeof value === "bigint");
  194. this.__expect(typeof this.target === typeof value);
  195. }
  196. toBeLessThan(value) {
  197. this.__validateNumericComparisonTypes(value);
  198. this.__doMatcher(() => {
  199. this.__expect(this.target < value);
  200. });
  201. }
  202. toBeLessThanOrEqual(value) {
  203. this.__validateNumericComparisonTypes(value);
  204. this.__doMatcher(() => {
  205. this.__expect(this.target <= value);
  206. });
  207. }
  208. toBeGreaterThan(value) {
  209. this.__validateNumericComparisonTypes(value);
  210. this.__doMatcher(() => {
  211. this.__expect(this.target > value);
  212. });
  213. }
  214. toBeGreaterThanOrEqual(value) {
  215. this.__validateNumericComparisonTypes(value);
  216. this.__doMatcher(() => {
  217. this.__expect(this.target >= value);
  218. });
  219. }
  220. toContain(item) {
  221. this.__doMatcher(() => {
  222. for (let element of this.target) {
  223. if (item === element) return;
  224. }
  225. throw new ExpectationError();
  226. });
  227. }
  228. toContainEqual(item) {
  229. this.__doMatcher(() => {
  230. for (let element of this.target) {
  231. if (deepEquals(item, element)) return;
  232. }
  233. throw new ExpectationError();
  234. });
  235. }
  236. toEqual(value) {
  237. this.__doMatcher(() => {
  238. this.__expect(
  239. deepEquals(this.target, value),
  240. () =>
  241. `Expected _${valueToString(value)}_, but got _${valueToString(
  242. this.target
  243. )}_`
  244. );
  245. });
  246. }
  247. toThrow(value) {
  248. this.__expect(typeof this.target === "function");
  249. this.__expect(
  250. typeof value === "string" ||
  251. typeof value === "function" ||
  252. typeof value === "object" ||
  253. value === undefined
  254. );
  255. this.__doMatcher(() => {
  256. let threw = true;
  257. try {
  258. this.target();
  259. threw = false;
  260. } catch (e) {
  261. if (typeof value === "string") {
  262. this.__expect(
  263. e.message.includes(value),
  264. `Expected ${this.target.toString()} to throw and message to include "${value}" but message "${
  265. e.message
  266. }" did not contain it`
  267. );
  268. } else if (typeof value === "function") {
  269. this.__expect(
  270. e instanceof value,
  271. `Expected ${this.target.toString()} to throw and be of type ${value} but it threw ${e}`
  272. );
  273. } else if (typeof value === "object") {
  274. this.__expect(
  275. e.message === value.message,
  276. `Expected ${this.target.toString()} to throw and message to be ${value} but it threw with message ${
  277. e.message
  278. }`
  279. );
  280. }
  281. }
  282. this.__expect(
  283. threw,
  284. `Expected ${this.target.toString()} to throw but it didn't throw anything`
  285. );
  286. });
  287. }
  288. pass(message) {
  289. // FIXME: This does nothing. If we want to implement things
  290. // like assertion count, this will have to do something
  291. }
  292. // jest-extended
  293. fail(message) {
  294. this.__doMatcher(() => {
  295. this.__expect(false, message);
  296. });
  297. }
  298. // jest-extended
  299. toThrowWithMessage(class_, message) {
  300. this.__expect(typeof this.target === "function");
  301. this.__expect(class_ !== undefined);
  302. this.__expect(message !== undefined);
  303. this.__doMatcher(() => {
  304. try {
  305. this.target();
  306. this.__expect(false, () => "toThrowWithMessage: target function did not throw");
  307. } catch (e) {
  308. this.__expect(
  309. e instanceof class_,
  310. () =>
  311. `toThrowWithMessage: expected error to be instance of ${valueToString(
  312. class_.name
  313. )}, got ${valueToString(e.name)}`
  314. );
  315. this.__expect(
  316. e.message.includes(message),
  317. () =>
  318. `toThrowWithMessage: expected error message to include _${valueToString(
  319. message
  320. )}_, got _${valueToString(e.message)}_`
  321. );
  322. }
  323. });
  324. }
  325. // Test for syntax errors; target must be a string
  326. toEval() {
  327. this.__expect(typeof this.target === "string");
  328. const success = canParseSource(this.target);
  329. this.__expect(
  330. this.inverted ? !success : success,
  331. () =>
  332. `Expected _${valueToString(this.target)}_ ` +
  333. (this.inverted ? "not to eval but it did" : "to eval but it didn't")
  334. );
  335. }
  336. // Must compile regardless of inverted-ness
  337. toEvalTo(value) {
  338. this.__expect(typeof this.target === "string");
  339. let result;
  340. try {
  341. result = eval(this.target);
  342. } catch (e) {
  343. throw new ExpectationError(
  344. `Expected _${valueToString(this.target)}_ to eval but it failed with ${e}`
  345. );
  346. }
  347. this.__doMatcher(() => {
  348. this.__expect(
  349. deepEquals(value, result),
  350. () =>
  351. `Expected _${valueToString(this.target)}_ to eval to ` +
  352. `_${valueToString(value)}_ but got _${valueToString(result)}_`
  353. );
  354. });
  355. }
  356. toHaveConfigurableProperty(property) {
  357. this.__expect(this.target !== undefined && this.target !== null);
  358. let d = Object.getOwnPropertyDescriptor(this.target, property);
  359. this.__expect(d !== undefined);
  360. this.__doMatcher(() => {
  361. this.__expect(d.configurable);
  362. });
  363. }
  364. toHaveEnumerableProperty(property) {
  365. this.__expect(this.target !== undefined && this.target !== null);
  366. let d = Object.getOwnPropertyDescriptor(this.target, property);
  367. this.__expect(d !== undefined);
  368. this.__doMatcher(() => {
  369. this.__expect(d.enumerable);
  370. });
  371. }
  372. toHaveWritableProperty(property) {
  373. this.__expect(this.target !== undefined && this.target !== null);
  374. let d = Object.getOwnPropertyDescriptor(this.target, property);
  375. this.__expect(d !== undefined);
  376. this.__doMatcher(() => {
  377. this.__expect(d.writable);
  378. });
  379. }
  380. toHaveValueProperty(property, value) {
  381. this.__expect(this.target !== undefined && this.target !== null);
  382. let d = Object.getOwnPropertyDescriptor(this.target, property);
  383. this.__expect(d !== undefined);
  384. this.__doMatcher(() => {
  385. this.__expect(d.value !== undefined);
  386. if (value !== undefined) this.__expect(deepEquals(value, d.value));
  387. });
  388. }
  389. toHaveGetterProperty(property) {
  390. this.__expect(this.target !== undefined && this.target !== null);
  391. let d = Object.getOwnPropertyDescriptor(this.target, property);
  392. this.__expect(d !== undefined);
  393. this.__doMatcher(() => {
  394. this.__expect(d.get !== undefined);
  395. });
  396. }
  397. toHaveSetterProperty(property) {
  398. this.__expect(this.target !== undefined && this.target !== null);
  399. let d = Object.getOwnPropertyDescriptor(this.target, property);
  400. this.__expect(d !== undefined);
  401. this.__doMatcher(() => {
  402. this.__expect(d.set !== undefined);
  403. });
  404. }
  405. toBeIteratorResultWithValue(value) {
  406. this.__expect(this.target !== undefined && this.target !== null);
  407. this.__doMatcher(() => {
  408. this.__expect(
  409. this.target.done === false,
  410. () =>
  411. `toGiveIteratorResultWithValue: expected 'done' to be _false_ got ${valueToString(
  412. this.target.done
  413. )}`
  414. );
  415. this.__expect(
  416. deepEquals(value, this.target.value),
  417. () =>
  418. `toGiveIteratorResultWithValue: expected 'value' to be _${valueToString(
  419. value
  420. )}_ got ${valueToString(this.target.value)}`
  421. );
  422. });
  423. }
  424. toBeIteratorResultDone() {
  425. this.__expect(this.target !== undefined && this.target !== null);
  426. this.__doMatcher(() => {
  427. this.__expect(
  428. this.target.done === true,
  429. () =>
  430. `toGiveIteratorResultDone: expected 'done' to be _true_ got ${valueToString(
  431. this.target.done
  432. )}`
  433. );
  434. this.__expect(
  435. this.target.value === undefined,
  436. () =>
  437. `toGiveIteratorResultDone: expected 'value' to be _undefined_ got ${valueToString(
  438. this.target.value
  439. )}`
  440. );
  441. });
  442. }
  443. __doMatcher(matcher) {
  444. if (!this.inverted) {
  445. matcher();
  446. } else {
  447. let threw = false;
  448. try {
  449. matcher();
  450. } catch (e) {
  451. if (e.name === "ExpectationError") threw = true;
  452. }
  453. if (!threw) throw new ExpectationError("not: test didn't fail");
  454. }
  455. }
  456. __expect(value, details) {
  457. if (value !== true) {
  458. if (details !== undefined) {
  459. if (details instanceof Function) throw new ExpectationError(details());
  460. else throw new ExpectationError(details);
  461. } else {
  462. throw new ExpectationError();
  463. }
  464. }
  465. }
  466. }
  467. expect = value => new Expector(value);
  468. // describe is able to lump test results inside of it by using this context
  469. // variable. Top level tests have the default suite message
  470. const defaultSuiteMessage = "__$$TOP_LEVEL$$__";
  471. let suiteMessage = defaultSuiteMessage;
  472. describe = (message, callback) => {
  473. suiteMessage = message;
  474. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  475. try {
  476. callback();
  477. } catch (e) {
  478. __TestResults__[suiteMessage][defaultSuiteMessage] = {
  479. result: "fail",
  480. details: String(e),
  481. duration: 0,
  482. };
  483. }
  484. suiteMessage = defaultSuiteMessage;
  485. };
  486. test = (message, callback) => {
  487. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  488. const suite = __TestResults__[suiteMessage];
  489. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  490. suite[message] = {
  491. result: "fail",
  492. details: "Another test with the same message did already run",
  493. duration: 0,
  494. };
  495. return;
  496. }
  497. const now = () => Temporal.Now.instant().epochNanoseconds;
  498. const start = now();
  499. const time_us = () => Number(BigInt.asIntN(53, (now() - start) / 1000n));
  500. try {
  501. callback();
  502. suite[message] = {
  503. result: "pass",
  504. duration: time_us(),
  505. };
  506. } catch (e) {
  507. suite[message] = {
  508. result: "fail",
  509. details: String(e),
  510. duration: time_us(),
  511. };
  512. }
  513. };
  514. test.skip = (message, callback) => {
  515. if (typeof callback !== "function")
  516. throw new Error("test.skip has invalid second argument (must be a function)");
  517. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  518. const suite = __TestResults__[suiteMessage];
  519. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  520. suite[message] = {
  521. result: "fail",
  522. details: "Another test with the same message did already run",
  523. duration: 0,
  524. };
  525. return;
  526. }
  527. suite[message] = {
  528. result: "skip",
  529. duration: 0,
  530. };
  531. };
  532. withinSameSecond = callback => {
  533. let callbackDuration;
  534. for (let tries = 0; tries < 5; tries++) {
  535. const start = Temporal.Now.instant();
  536. const result = callback();
  537. const end = Temporal.Now.instant();
  538. if (start.epochSeconds !== end.epochSeconds) {
  539. callbackDuration = start.until(end);
  540. continue;
  541. }
  542. return result;
  543. }
  544. throw new ExpectationError(
  545. `Tried to execute callback '${callback}' 5 times within the same second but ` +
  546. `failed. Make sure the callback does as little work as possible (the last run ` +
  547. `took ${callbackDuration.total(
  548. "milliseconds"
  549. )} ms) and the machine is not overloaded. If you see this ` +
  550. `error appearing in the CI it is most likely a flaky failure!`
  551. );
  552. };
  553. })();