test-common.js 20 KB

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