test-common.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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(
  125. object !== undefined && object !== null,
  126. "got undefined or null as array key"
  127. );
  128. object = object[key];
  129. }
  130. } else {
  131. object = object[property];
  132. }
  133. this.__expect(object !== undefined, "should not be undefined");
  134. if (value !== undefined)
  135. this.__expect(
  136. deepEquals(object, value),
  137. `value does not equal property ${valueToString(object)} vs ${valueToString(
  138. value
  139. )}`
  140. );
  141. });
  142. }
  143. toBeDefined() {
  144. this.__doMatcher(() => {
  145. this.__expect(
  146. this.target !== undefined,
  147. () => "toBeDefined: expected target to be defined, got undefined"
  148. );
  149. });
  150. }
  151. toBeInstanceOf(class_) {
  152. this.__doMatcher(() => {
  153. this.__expect(
  154. this.target instanceof class_,
  155. `Expected ${valueToString(this.target)} to be instance of ${class_.name}`
  156. );
  157. });
  158. }
  159. toBeNull() {
  160. this.__doMatcher(() => {
  161. this.__expect(
  162. this.target === null,
  163. `Expected target to be null got ${valueToString(this.target)}`
  164. );
  165. });
  166. }
  167. toBeUndefined() {
  168. this.__doMatcher(() => {
  169. this.__expect(
  170. this.target === undefined,
  171. () =>
  172. `toBeUndefined: expected target to be undefined, got _${valueToString(
  173. this.target
  174. )}_`
  175. );
  176. });
  177. }
  178. toBeNaN() {
  179. this.__doMatcher(() => {
  180. this.__expect(
  181. isNaN(this.target),
  182. () => `toBeNaN: expected target to be NaN, got _${valueToString(this.target)}_`
  183. );
  184. });
  185. }
  186. toBeTrue() {
  187. this.__doMatcher(() => {
  188. this.__expect(
  189. this.target === true,
  190. () =>
  191. `toBeTrue: expected target to be true, got _${valueToString(this.target)}_`
  192. );
  193. });
  194. }
  195. toBeFalse() {
  196. this.__doMatcher(() => {
  197. this.__expect(
  198. this.target === false,
  199. () =>
  200. `toBeFalse: expected target to be false, got _${valueToString(
  201. this.target
  202. )}_`
  203. );
  204. });
  205. }
  206. __validateNumericComparisonTypes(value) {
  207. this.__expect(typeof this.target === "number" || typeof this.target === "bigint");
  208. this.__expect(typeof value === "number" || typeof value === "bigint");
  209. this.__expect(typeof this.target === typeof value);
  210. }
  211. toBeLessThan(value) {
  212. this.__validateNumericComparisonTypes(value);
  213. this.__doMatcher(() => {
  214. this.__expect(this.target < value);
  215. });
  216. }
  217. toBeLessThanOrEqual(value) {
  218. this.__validateNumericComparisonTypes(value);
  219. this.__doMatcher(() => {
  220. this.__expect(this.target <= value);
  221. });
  222. }
  223. toBeGreaterThan(value) {
  224. this.__validateNumericComparisonTypes(value);
  225. this.__doMatcher(() => {
  226. this.__expect(this.target > value);
  227. });
  228. }
  229. toBeGreaterThanOrEqual(value) {
  230. this.__validateNumericComparisonTypes(value);
  231. this.__doMatcher(() => {
  232. this.__expect(this.target >= value);
  233. });
  234. }
  235. toContain(item) {
  236. this.__doMatcher(() => {
  237. for (let element of this.target) {
  238. if (item === element) return;
  239. }
  240. throw new ExpectationError();
  241. });
  242. }
  243. toContainEqual(item) {
  244. this.__doMatcher(() => {
  245. for (let element of this.target) {
  246. if (deepEquals(item, element)) return;
  247. }
  248. throw new ExpectationError();
  249. });
  250. }
  251. toEqual(value) {
  252. this.__doMatcher(() => {
  253. this.__expect(
  254. deepEquals(this.target, value),
  255. () =>
  256. `Expected _${valueToString(value)}_, but got _${valueToString(
  257. this.target
  258. )}_`
  259. );
  260. });
  261. }
  262. toThrow(value) {
  263. this.__expect(typeof this.target === "function");
  264. this.__expect(
  265. typeof value === "string" ||
  266. typeof value === "function" ||
  267. typeof value === "object" ||
  268. value === undefined
  269. );
  270. this.__doMatcher(() => {
  271. let threw = true;
  272. try {
  273. this.target();
  274. threw = false;
  275. } catch (e) {
  276. if (typeof value === "string") {
  277. this.__expect(
  278. e.message.includes(value),
  279. `Expected ${this.target.toString()} to throw and message to include "${value}" but message "${
  280. e.message
  281. }" did not contain it`
  282. );
  283. } else if (typeof value === "function") {
  284. this.__expect(
  285. e instanceof value,
  286. `Expected ${this.target.toString()} to throw and be of type ${value} but it threw ${e}`
  287. );
  288. } else if (typeof value === "object") {
  289. this.__expect(
  290. e.message === value.message,
  291. `Expected ${this.target.toString()} to throw and message to be ${value} but it threw with message ${
  292. e.message
  293. }`
  294. );
  295. }
  296. }
  297. this.__expect(
  298. threw,
  299. `Expected ${this.target.toString()} to throw but it didn't throw anything`
  300. );
  301. });
  302. }
  303. pass(message) {
  304. // FIXME: This does nothing. If we want to implement things
  305. // like assertion count, this will have to do something
  306. }
  307. // jest-extended
  308. fail(message) {
  309. this.__doMatcher(() => {
  310. this.__expect(false, message);
  311. });
  312. }
  313. // jest-extended
  314. toThrowWithMessage(class_, message) {
  315. this.__expect(typeof this.target === "function");
  316. this.__expect(class_ !== undefined);
  317. this.__expect(message !== undefined);
  318. this.__doMatcher(() => {
  319. try {
  320. this.target();
  321. this.__expect(false, () => "toThrowWithMessage: target function did not throw");
  322. } catch (e) {
  323. this.__expect(
  324. e instanceof class_,
  325. () =>
  326. `toThrowWithMessage: expected error to be instance of ${valueToString(
  327. class_.name
  328. )}, got ${valueToString(e.name)}`
  329. );
  330. this.__expect(
  331. e.message.includes(message),
  332. () =>
  333. `toThrowWithMessage: expected error message to include _${valueToString(
  334. message
  335. )}_, got _${valueToString(e.message)}_`
  336. );
  337. }
  338. });
  339. }
  340. // Test for syntax errors; target must be a string
  341. toEval() {
  342. this.__expect(typeof this.target === "string");
  343. const success = canParseSource(this.target);
  344. this.__expect(
  345. this.inverted ? !success : success,
  346. () =>
  347. `Expected _${valueToString(this.target)}_ ` +
  348. (this.inverted ? "not to eval but it did" : "to eval but it didn't")
  349. );
  350. }
  351. // Must compile regardless of inverted-ness
  352. toEvalTo(value) {
  353. this.__expect(typeof this.target === "string");
  354. let result;
  355. try {
  356. result = eval(this.target);
  357. } catch (e) {
  358. throw new ExpectationError(
  359. `Expected _${valueToString(this.target)}_ to eval but it failed with ${e}`
  360. );
  361. }
  362. this.__doMatcher(() => {
  363. this.__expect(
  364. deepEquals(value, result),
  365. () =>
  366. `Expected _${valueToString(this.target)}_ to eval to ` +
  367. `_${valueToString(value)}_ but got _${valueToString(result)}_`
  368. );
  369. });
  370. }
  371. toHaveConfigurableProperty(property) {
  372. this.__expect(this.target !== undefined && this.target !== null);
  373. let d = Object.getOwnPropertyDescriptor(this.target, property);
  374. this.__expect(d !== undefined);
  375. this.__doMatcher(() => {
  376. this.__expect(d.configurable);
  377. });
  378. }
  379. toHaveEnumerableProperty(property) {
  380. this.__expect(this.target !== undefined && this.target !== null);
  381. let d = Object.getOwnPropertyDescriptor(this.target, property);
  382. this.__expect(d !== undefined);
  383. this.__doMatcher(() => {
  384. this.__expect(d.enumerable);
  385. });
  386. }
  387. toHaveWritableProperty(property) {
  388. this.__expect(this.target !== undefined && this.target !== null);
  389. let d = Object.getOwnPropertyDescriptor(this.target, property);
  390. this.__expect(d !== undefined);
  391. this.__doMatcher(() => {
  392. this.__expect(d.writable);
  393. });
  394. }
  395. toHaveValueProperty(property, value) {
  396. this.__expect(this.target !== undefined && this.target !== null);
  397. let d = Object.getOwnPropertyDescriptor(this.target, property);
  398. this.__expect(d !== undefined);
  399. this.__doMatcher(() => {
  400. this.__expect(d.value !== undefined);
  401. if (value !== undefined) this.__expect(deepEquals(value, d.value));
  402. });
  403. }
  404. toHaveGetterProperty(property) {
  405. this.__expect(this.target !== undefined && this.target !== null);
  406. let d = Object.getOwnPropertyDescriptor(this.target, property);
  407. this.__expect(d !== undefined);
  408. this.__doMatcher(() => {
  409. this.__expect(d.get !== undefined);
  410. });
  411. }
  412. toHaveSetterProperty(property) {
  413. this.__expect(this.target !== undefined && this.target !== null);
  414. let d = Object.getOwnPropertyDescriptor(this.target, property);
  415. this.__expect(d !== undefined);
  416. this.__doMatcher(() => {
  417. this.__expect(d.set !== undefined);
  418. });
  419. }
  420. toBeIteratorResultWithValue(value) {
  421. this.__expect(this.target !== undefined && this.target !== null);
  422. this.__doMatcher(() => {
  423. this.__expect(
  424. this.target.done === false,
  425. () =>
  426. `toGiveIteratorResultWithValue: expected 'done' to be _false_ got ${valueToString(
  427. this.target.done
  428. )}`
  429. );
  430. this.__expect(
  431. deepEquals(value, this.target.value),
  432. () =>
  433. `toGiveIteratorResultWithValue: expected 'value' to be _${valueToString(
  434. value
  435. )}_ got ${valueToString(this.target.value)}`
  436. );
  437. });
  438. }
  439. toBeIteratorResultDone() {
  440. this.__expect(this.target !== undefined && this.target !== null);
  441. this.__doMatcher(() => {
  442. this.__expect(
  443. this.target.done === true,
  444. () =>
  445. `toGiveIteratorResultDone: expected 'done' to be _true_ got ${valueToString(
  446. this.target.done
  447. )}`
  448. );
  449. this.__expect(
  450. this.target.value === undefined,
  451. () =>
  452. `toGiveIteratorResultDone: expected 'value' to be _undefined_ got ${valueToString(
  453. this.target.value
  454. )}`
  455. );
  456. });
  457. }
  458. __doMatcher(matcher) {
  459. if (!this.inverted) {
  460. matcher();
  461. } else {
  462. let threw = false;
  463. try {
  464. matcher();
  465. } catch (e) {
  466. if (e.name === "ExpectationError") threw = true;
  467. }
  468. if (!threw) throw new ExpectationError("not: test didn't fail");
  469. }
  470. }
  471. __expect(value, details) {
  472. if (value !== true) {
  473. if (details !== undefined) {
  474. if (details instanceof Function) throw new ExpectationError(details());
  475. else throw new ExpectationError(details);
  476. } else {
  477. throw new ExpectationError();
  478. }
  479. }
  480. }
  481. }
  482. expect = value => new Expector(value);
  483. // describe is able to lump test results inside of it by using this context
  484. // variable. Top level tests have the default suite message
  485. const defaultSuiteMessage = "__$$TOP_LEVEL$$__";
  486. let suiteMessage = defaultSuiteMessage;
  487. describe = (message, callback) => {
  488. suiteMessage = message;
  489. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  490. try {
  491. callback();
  492. } catch (e) {
  493. __TestResults__[suiteMessage][defaultSuiteMessage] = {
  494. result: "fail",
  495. details: String(e),
  496. duration: 0,
  497. };
  498. }
  499. suiteMessage = defaultSuiteMessage;
  500. };
  501. test = (message, callback) => {
  502. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  503. const suite = __TestResults__[suiteMessage];
  504. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  505. suite[message] = {
  506. result: "fail",
  507. details: "Another test with the same message did already run",
  508. duration: 0,
  509. };
  510. return;
  511. }
  512. const now = () => Temporal.Now.instant().epochNanoseconds;
  513. const start = now();
  514. const time_us = () => Number(BigInt.asIntN(53, (now() - start) / 1000n));
  515. try {
  516. callback();
  517. suite[message] = {
  518. result: "pass",
  519. duration: time_us(),
  520. };
  521. } catch (e) {
  522. suite[message] = {
  523. result: "fail",
  524. details: String(e),
  525. duration: time_us(),
  526. };
  527. }
  528. };
  529. test.skip = (message, callback) => {
  530. if (typeof callback !== "function")
  531. throw new Error("test.skip has invalid second argument (must be a function)");
  532. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  533. const suite = __TestResults__[suiteMessage];
  534. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  535. suite[message] = {
  536. result: "fail",
  537. details: "Another test with the same message did already run",
  538. duration: 0,
  539. };
  540. return;
  541. }
  542. suite[message] = {
  543. result: "skip",
  544. duration: 0,
  545. };
  546. };
  547. withinSameSecond = callback => {
  548. let callbackDuration;
  549. for (let tries = 0; tries < 5; tries++) {
  550. const start = Temporal.Now.instant();
  551. const result = callback();
  552. const end = Temporal.Now.instant();
  553. if (start.epochSeconds !== end.epochSeconds) {
  554. callbackDuration = start.until(end);
  555. continue;
  556. }
  557. return result;
  558. }
  559. throw new ExpectationError(
  560. `Tried to execute callback '${callback}' 5 times within the same second but ` +
  561. `failed. Make sure the callback does as little work as possible (the last run ` +
  562. `took ${callbackDuration.total(
  563. "milliseconds"
  564. )} ms) and the machine is not overloaded. If you see this ` +
  565. `error appearing in the CI it is most likely a flaky failure!`
  566. );
  567. };
  568. })();