test-common.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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(e.message.includes(value));
  262. } else if (typeof value === "function") {
  263. this.__expect(e instanceof value);
  264. } else if (typeof value === "object") {
  265. this.__expect(e.message === value.message);
  266. }
  267. }
  268. this.__expect(threw);
  269. });
  270. }
  271. pass(message) {
  272. // FIXME: This does nothing. If we want to implement things
  273. // like assertion count, this will have to do something
  274. }
  275. // jest-extended
  276. fail(message) {
  277. this.__doMatcher(() => {
  278. this.__expect(false, message);
  279. });
  280. }
  281. // jest-extended
  282. toThrowWithMessage(class_, message) {
  283. this.__expect(typeof this.target === "function");
  284. this.__expect(class_ !== undefined);
  285. this.__expect(message !== undefined);
  286. this.__doMatcher(() => {
  287. try {
  288. this.target();
  289. this.__expect(false, () => "toThrowWithMessage: target function did not throw");
  290. } catch (e) {
  291. this.__expect(
  292. e instanceof class_,
  293. () =>
  294. `toThrowWithMessage: expected error to be instance of ${valueToString(
  295. class_.name
  296. )}, got ${valueToString(e.name)}`
  297. );
  298. this.__expect(
  299. e.message.includes(message),
  300. () =>
  301. `toThrowWithMessage: expected error message to include _${valueToString(
  302. message
  303. )}_, got _${valueToString(e.message)}_`
  304. );
  305. }
  306. });
  307. }
  308. // Test for syntax errors; target must be a string
  309. toEval() {
  310. this.__expect(typeof this.target === "string");
  311. const success = canParseSource(this.target);
  312. this.__expect(
  313. this.inverted ? !success : success,
  314. () =>
  315. `Expected _${valueToString(this.target)}_` +
  316. (this.inverted ? "not to eval but it did" : "to eval but it didn't")
  317. );
  318. }
  319. // Must compile regardless of inverted-ness
  320. toEvalTo(value) {
  321. this.__expect(typeof this.target === "string");
  322. let result;
  323. try {
  324. result = eval(this.target);
  325. } catch (e) {
  326. throw new ExpectationError(
  327. `Expected _${valueToString(this.target)}_ to eval but it failed with ${e}`
  328. );
  329. }
  330. this.__doMatcher(() => {
  331. this.__expect(
  332. deepEquals(value, result),
  333. () =>
  334. `Expected _${valueToString(this.target)}_ to eval to ` +
  335. `_${valueToString(value)}_ but got _${valueToString(result)}_`
  336. );
  337. });
  338. }
  339. toHaveConfigurableProperty(property) {
  340. this.__expect(this.target !== undefined && this.target !== null);
  341. let d = Object.getOwnPropertyDescriptor(this.target, property);
  342. this.__expect(d !== undefined);
  343. this.__doMatcher(() => {
  344. this.__expect(d.configurable);
  345. });
  346. }
  347. toHaveEnumerableProperty(property) {
  348. this.__expect(this.target !== undefined && this.target !== null);
  349. let d = Object.getOwnPropertyDescriptor(this.target, property);
  350. this.__expect(d !== undefined);
  351. this.__doMatcher(() => {
  352. this.__expect(d.enumerable);
  353. });
  354. }
  355. toHaveWritableProperty(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.writable);
  361. });
  362. }
  363. toHaveValueProperty(property, value) {
  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.value !== undefined);
  369. if (value !== undefined) this.__expect(deepEquals(value, d.value));
  370. });
  371. }
  372. toHaveGetterProperty(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.get !== undefined);
  378. });
  379. }
  380. toHaveSetterProperty(property) {
  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.set !== undefined);
  386. });
  387. }
  388. toBeIteratorResultWithValue(value) {
  389. this.__expect(this.target !== undefined && this.target !== null);
  390. this.__doMatcher(() => {
  391. this.__expect(
  392. this.target.done === false,
  393. () =>
  394. `toGiveIteratorResultWithValue: expected 'done' to be _false_ got ${valueToString(
  395. this.target.done
  396. )}`
  397. );
  398. this.__expect(
  399. deepEquals(value, this.target.value),
  400. () =>
  401. `toGiveIteratorResultWithValue: expected 'value' to be _${valueToString(
  402. value
  403. )}_ got ${valueToString(this.target.value)}`
  404. );
  405. });
  406. }
  407. toBeIteratorResultDone() {
  408. this.__expect(this.target !== undefined && this.target !== null);
  409. this.__doMatcher(() => {
  410. this.__expect(
  411. this.target.done === true,
  412. () =>
  413. `toGiveIteratorResultDone: expected 'done' to be _true_ got ${valueToString(
  414. this.target.done
  415. )}`
  416. );
  417. this.__expect(
  418. this.target.value === undefined,
  419. () =>
  420. `toGiveIteratorResultDone: expected 'value' to be _undefined_ got ${valueToString(
  421. this.target.value
  422. )}`
  423. );
  424. });
  425. }
  426. __doMatcher(matcher) {
  427. if (!this.inverted) {
  428. matcher();
  429. } else {
  430. let threw = false;
  431. try {
  432. matcher();
  433. } catch (e) {
  434. if (e.name === "ExpectationError") threw = true;
  435. }
  436. if (!threw) throw new ExpectationError("not: test didn't fail");
  437. }
  438. }
  439. __expect(value, details) {
  440. if (value !== true) {
  441. if (details !== undefined) {
  442. if (details instanceof Function) throw new ExpectationError(details());
  443. else throw new ExpectationError(details);
  444. } else {
  445. throw new ExpectationError();
  446. }
  447. }
  448. }
  449. }
  450. expect = value => new Expector(value);
  451. // describe is able to lump test results inside of it by using this context
  452. // variable. Top level tests have the default suite message
  453. const defaultSuiteMessage = "__$$TOP_LEVEL$$__";
  454. let suiteMessage = defaultSuiteMessage;
  455. describe = (message, callback) => {
  456. suiteMessage = message;
  457. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  458. try {
  459. callback();
  460. } catch (e) {
  461. __TestResults__[suiteMessage][defaultSuiteMessage] = {
  462. result: "fail",
  463. details: String(e),
  464. duration: 0,
  465. };
  466. }
  467. suiteMessage = defaultSuiteMessage;
  468. };
  469. test = (message, callback) => {
  470. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  471. const suite = __TestResults__[suiteMessage];
  472. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  473. suite[message] = {
  474. result: "fail",
  475. details: "Another test with the same message did already run",
  476. duration: 0,
  477. };
  478. return;
  479. }
  480. const now = () => Temporal.Now.instant().epochNanoseconds;
  481. const start = now();
  482. const time_us = () => Number(BigInt.asIntN(53, (now() - start) / 1000n));
  483. try {
  484. callback();
  485. suite[message] = {
  486. result: "pass",
  487. duration: time_us(),
  488. };
  489. } catch (e) {
  490. suite[message] = {
  491. result: "fail",
  492. details: String(e),
  493. duration: time_us(),
  494. };
  495. }
  496. };
  497. test.skip = (message, callback) => {
  498. if (typeof callback !== "function")
  499. throw new Error("test.skip has invalid second argument (must be a function)");
  500. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  501. const suite = __TestResults__[suiteMessage];
  502. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  503. suite[message] = {
  504. result: "fail",
  505. details: "Another test with the same message did already run",
  506. duration: 0,
  507. };
  508. return;
  509. }
  510. suite[message] = {
  511. result: "skip",
  512. duration: 0,
  513. };
  514. };
  515. })();