test-common.js 16 KB

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