test-common.js 16 KB

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