test-common.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. let describe;
  2. let test;
  3. let expect;
  4. // Stores the results of each test and suite. Has a terrible
  5. // name to avoid name collision.
  6. let __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. let __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 => Object.prototype.toString.call(value);
  46. class Expector {
  47. constructor(target, inverted) {
  48. this.target = target;
  49. this.inverted = !!inverted;
  50. }
  51. get not() {
  52. return new Expector(this.target, !this.inverted);
  53. }
  54. toBe(value) {
  55. this.__doMatcher(() => {
  56. this.__expect(
  57. Object.is(this.target, value),
  58. () =>
  59. `toBe: expected _${valueToString(value)}_, got _${valueToString(
  60. this.target
  61. )}_`
  62. );
  63. });
  64. }
  65. // FIXME: Take a precision argument like jest's toBeCloseTo matcher
  66. toBeCloseTo(value) {
  67. this.__expect(
  68. typeof this.target === "number",
  69. () => `toBeCloseTo: expected target of type number, got ${typeof value}`
  70. );
  71. this.__expect(
  72. typeof value === "number",
  73. () => `toBeCloseTo: expected argument of type number, got ${typeof value}`
  74. );
  75. this.__doMatcher(() => {
  76. this.__expect(Math.abs(this.target - value) < 0.000001);
  77. });
  78. }
  79. toHaveLength(length) {
  80. this.__expect(
  81. typeof this.target.length === "number",
  82. () => "toHaveLength: target.length not of type number"
  83. );
  84. this.__doMatcher(() => {
  85. this.__expect(Object.is(this.target.length, length));
  86. });
  87. }
  88. toHaveSize(size) {
  89. this.__expect(
  90. typeof this.target.size === "number",
  91. () => "toHaveSize: target.size not of type number"
  92. );
  93. this.__doMatcher(() => {
  94. this.__expect(Object.is(this.target.size, size));
  95. });
  96. }
  97. toHaveProperty(property, value) {
  98. this.__doMatcher(() => {
  99. let object = this.target;
  100. if (typeof property === "string" && property.includes(".")) {
  101. let propertyArray = [];
  102. while (property.includes(".")) {
  103. let index = property.indexOf(".");
  104. propertyArray.push(property.substring(0, index));
  105. if (index + 1 >= property.length) break;
  106. property = property.substring(index + 1, property.length);
  107. }
  108. propertyArray.push(property);
  109. property = propertyArray;
  110. }
  111. if (Array.isArray(property)) {
  112. for (let key of property) {
  113. this.__expect(object !== undefined && object !== null);
  114. object = object[key];
  115. }
  116. } else {
  117. object = object[property];
  118. }
  119. this.__expect(object !== undefined);
  120. if (value !== undefined) this.__expect(deepEquals(object, value));
  121. });
  122. }
  123. toBeDefined() {
  124. this.__doMatcher(() => {
  125. this.__expect(
  126. this.target !== undefined,
  127. () => "toBeDefined: expected target to be defined, got undefined"
  128. );
  129. });
  130. }
  131. toBeInstanceOf(class_) {
  132. this.__doMatcher(() => {
  133. this.__expect(this.target instanceof class_);
  134. });
  135. }
  136. toBeNull() {
  137. this.__doMatcher(() => {
  138. this.__expect(this.target === null);
  139. });
  140. }
  141. toBeUndefined() {
  142. this.__doMatcher(() => {
  143. this.__expect(
  144. this.target === undefined,
  145. () =>
  146. `toBeUndefined: expected target to be undefined, got _${valueToString(
  147. this.target
  148. )}_`
  149. );
  150. });
  151. }
  152. toBeNaN() {
  153. this.__doMatcher(() => {
  154. this.__expect(
  155. isNaN(this.target),
  156. () => `toBeNaN: expected target to be NaN, got _${valueToString(this.target)}_`
  157. );
  158. });
  159. }
  160. toBeTrue() {
  161. this.__doMatcher(() => {
  162. this.__expect(
  163. this.target === true,
  164. () =>
  165. `toBeTrue: expected target to be true, got _${valueToString(this.target)}_`
  166. );
  167. });
  168. }
  169. toBeFalse() {
  170. this.__doMatcher(() => {
  171. this.__expect(
  172. this.target === false,
  173. () =>
  174. `toBeTrue: expected target to be false, got _${valueToString(this.target)}_`
  175. );
  176. });
  177. }
  178. __validateNumericComparisonTypes(value) {
  179. this.__expect(typeof this.target === "number" || typeof this.target === "bigint");
  180. this.__expect(typeof value === "number" || typeof value === "bigint");
  181. this.__expect(typeof this.target === typeof value);
  182. }
  183. toBeLessThan(value) {
  184. this.__validateNumericComparisonTypes(value);
  185. this.__doMatcher(() => {
  186. this.__expect(this.target < value);
  187. });
  188. }
  189. toBeLessThanOrEqual(value) {
  190. this.__validateNumericComparisonTypes(value);
  191. this.__doMatcher(() => {
  192. this.__expect(this.target <= value);
  193. });
  194. }
  195. toBeGreaterThan(value) {
  196. this.__validateNumericComparisonTypes(value);
  197. this.__doMatcher(() => {
  198. this.__expect(this.target > value);
  199. });
  200. }
  201. toBeGreaterThanOrEqual(value) {
  202. this.__validateNumericComparisonTypes(value);
  203. this.__doMatcher(() => {
  204. this.__expect(this.target >= value);
  205. });
  206. }
  207. toContain(item) {
  208. this.__doMatcher(() => {
  209. for (let element of this.target) {
  210. if (item === element) return;
  211. }
  212. throw new ExpectationError();
  213. });
  214. }
  215. toContainEqual(item) {
  216. this.__doMatcher(() => {
  217. for (let element of this.target) {
  218. if (deepEquals(item, element)) return;
  219. }
  220. throw new ExpectationError();
  221. });
  222. }
  223. toEqual(value) {
  224. this.__doMatcher(() => {
  225. this.__expect(deepEquals(this.target, value));
  226. });
  227. }
  228. toThrow(value) {
  229. this.__expect(typeof this.target === "function");
  230. this.__expect(
  231. typeof value === "string" ||
  232. typeof value === "function" ||
  233. typeof value === "object" ||
  234. value === undefined
  235. );
  236. this.__doMatcher(() => {
  237. let threw = true;
  238. try {
  239. this.target();
  240. threw = false;
  241. } catch (e) {
  242. if (typeof value === "string") {
  243. this.__expect(e.message.includes(value));
  244. } else if (typeof value === "function") {
  245. this.__expect(e instanceof value);
  246. } else if (typeof value === "object") {
  247. this.__expect(e.message === value.message);
  248. }
  249. }
  250. this.__expect(threw);
  251. });
  252. }
  253. pass(message) {
  254. // FIXME: This does nothing. If we want to implement things
  255. // like assertion count, this will have to do something
  256. }
  257. // jest-extended
  258. fail(message) {
  259. this.__doMatcher(() => {
  260. this.__expect(false, message);
  261. });
  262. }
  263. // jest-extended
  264. toThrowWithMessage(class_, message) {
  265. this.__expect(typeof this.target === "function");
  266. this.__expect(class_ !== undefined);
  267. this.__expect(message !== undefined);
  268. this.__doMatcher(() => {
  269. try {
  270. this.target();
  271. this.__expect(false, () => "toThrowWithMessage: target function did not throw");
  272. } catch (e) {
  273. this.__expect(
  274. e instanceof class_,
  275. () =>
  276. `toThrowWithMessage: expected error to be instance of ${valueToString(
  277. class_.name
  278. )}, got ${valueToString(e.name)}`
  279. );
  280. this.__expect(
  281. e.message.includes(message),
  282. () =>
  283. `toThrowWithMessage: expected error message to include _${valueToString(
  284. message
  285. )}_, got _${valueToString(e.message)}_`
  286. );
  287. }
  288. });
  289. }
  290. // Test for syntax errors; target must be a string
  291. toEval() {
  292. this.__expect(typeof this.target === "string");
  293. const success = canParseSource(this.target);
  294. this.__expect(this.inverted ? !success : success);
  295. }
  296. // Must compile regardless of inverted-ness
  297. toEvalTo(value) {
  298. this.__expect(typeof this.target === "string");
  299. let result;
  300. try {
  301. result = eval(this.target);
  302. } catch (e) {
  303. throw new ExpectationError();
  304. }
  305. this.__doMatcher(() => {
  306. this.__expect(deepEquals(value, result));
  307. });
  308. }
  309. toHaveConfigurableProperty(property) {
  310. this.__expect(this.target !== undefined && this.target !== null);
  311. let d = Object.getOwnPropertyDescriptor(this.target, property);
  312. this.__expect(d !== undefined);
  313. this.__doMatcher(() => {
  314. this.__expect(d.configurable);
  315. });
  316. }
  317. toHaveEnumerableProperty(property) {
  318. this.__expect(this.target !== undefined && this.target !== null);
  319. let d = Object.getOwnPropertyDescriptor(this.target, property);
  320. this.__expect(d !== undefined);
  321. this.__doMatcher(() => {
  322. this.__expect(d.enumerable);
  323. });
  324. }
  325. toHaveWritableProperty(property) {
  326. this.__expect(this.target !== undefined && this.target !== null);
  327. let d = Object.getOwnPropertyDescriptor(this.target, property);
  328. this.__expect(d !== undefined);
  329. this.__doMatcher(() => {
  330. this.__expect(d.writable);
  331. });
  332. }
  333. toHaveValueProperty(property, value) {
  334. this.__expect(this.target !== undefined && this.target !== null);
  335. let d = Object.getOwnPropertyDescriptor(this.target, property);
  336. this.__expect(d !== undefined);
  337. this.__doMatcher(() => {
  338. this.__expect(d.value !== undefined);
  339. if (value !== undefined) this.__expect(deepEquals(value, d.value));
  340. });
  341. }
  342. toHaveGetterProperty(property) {
  343. this.__expect(this.target !== undefined && this.target !== null);
  344. let d = Object.getOwnPropertyDescriptor(this.target, property);
  345. this.__expect(d !== undefined);
  346. this.__doMatcher(() => {
  347. this.__expect(d.get !== undefined);
  348. });
  349. }
  350. toHaveSetterProperty(property) {
  351. this.__expect(this.target !== undefined && this.target !== null);
  352. let d = Object.getOwnPropertyDescriptor(this.target, property);
  353. this.__expect(d !== undefined);
  354. this.__doMatcher(() => {
  355. this.__expect(d.set !== undefined);
  356. });
  357. }
  358. __doMatcher(matcher) {
  359. if (!this.inverted) {
  360. matcher();
  361. } else {
  362. let threw = false;
  363. try {
  364. matcher();
  365. } catch (e) {
  366. if (e.name === "ExpectationError") threw = true;
  367. }
  368. if (!threw) throw new ExpectationError("not: test didn't fail");
  369. }
  370. }
  371. __expect(value, details) {
  372. if (value !== true) {
  373. if (details !== undefined) {
  374. throw new ExpectationError(details());
  375. } else {
  376. throw new ExpectationError();
  377. }
  378. }
  379. }
  380. }
  381. expect = value => new Expector(value);
  382. // describe is able to lump test results inside of it by using this context
  383. // variable. Top level tests have the default suite message
  384. const defaultSuiteMessage = "__$$TOP_LEVEL$$__";
  385. let suiteMessage = defaultSuiteMessage;
  386. describe = (message, callback) => {
  387. suiteMessage = message;
  388. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  389. try {
  390. callback();
  391. } catch (e) {
  392. __TestResults__[suiteMessage][defaultSuiteMessage] = {
  393. result: "fail",
  394. details: String(e),
  395. };
  396. }
  397. suiteMessage = defaultSuiteMessage;
  398. };
  399. test = (message, callback) => {
  400. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  401. const suite = __TestResults__[suiteMessage];
  402. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  403. suite[message] = {
  404. result: "fail",
  405. details: "Another test with the same message did already run",
  406. };
  407. return;
  408. }
  409. try {
  410. callback();
  411. suite[message] = {
  412. result: "pass",
  413. };
  414. } catch (e) {
  415. suite[message] = {
  416. result: "fail",
  417. details: String(e),
  418. };
  419. }
  420. };
  421. test.skip = (message, callback) => {
  422. if (typeof callback !== "function")
  423. throw new Error("test.skip has invalid second argument (must be a function)");
  424. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  425. const suite = __TestResults__[suiteMessage];
  426. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  427. suite[message] = {
  428. result: "fail",
  429. details: "Another test with the same message did already run",
  430. };
  431. return;
  432. }
  433. suite[message] = {
  434. result: "skip",
  435. };
  436. };
  437. })();