test-common.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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(this.target === true);
  150. });
  151. }
  152. toBeFalse() {
  153. this.__doMatcher(() => {
  154. this.__expect(this.target === false);
  155. });
  156. }
  157. __validateNumericComparisonTypes(value) {
  158. this.__expect(typeof this.target === "number" || typeof this.target === "bigint");
  159. this.__expect(typeof value === "number" || typeof value === "bigint");
  160. this.__expect(typeof this.target === typeof value);
  161. }
  162. toBeLessThan(value) {
  163. this.__validateNumericComparisonTypes(value);
  164. this.__doMatcher(() => {
  165. this.__expect(this.target < value);
  166. });
  167. }
  168. toBeLessThanOrEqual(value) {
  169. this.__validateNumericComparisonTypes(value);
  170. this.__doMatcher(() => {
  171. this.__expect(this.target <= value);
  172. });
  173. }
  174. toBeGreaterThan(value) {
  175. this.__validateNumericComparisonTypes(value);
  176. this.__doMatcher(() => {
  177. this.__expect(this.target > value);
  178. });
  179. }
  180. toBeGreaterThanOrEqual(value) {
  181. this.__validateNumericComparisonTypes(value);
  182. this.__doMatcher(() => {
  183. this.__expect(this.target >= value);
  184. });
  185. }
  186. toContain(item) {
  187. this.__doMatcher(() => {
  188. for (let element of this.target) {
  189. if (item === element) return;
  190. }
  191. throw new ExpectationError();
  192. });
  193. }
  194. toContainEqual(item) {
  195. this.__doMatcher(() => {
  196. for (let element of this.target) {
  197. if (deepEquals(item, element)) return;
  198. }
  199. throw new ExpectationError();
  200. });
  201. }
  202. toEqual(value) {
  203. this.__doMatcher(() => {
  204. this.__expect(deepEquals(this.target, value));
  205. });
  206. }
  207. toThrow(value) {
  208. this.__expect(typeof this.target === "function");
  209. this.__expect(
  210. typeof value === "string" ||
  211. typeof value === "function" ||
  212. typeof value === "object" ||
  213. value === undefined
  214. );
  215. this.__doMatcher(() => {
  216. let threw = true;
  217. try {
  218. this.target();
  219. threw = false;
  220. } catch (e) {
  221. if (typeof value === "string") {
  222. this.__expect(e.message.includes(value));
  223. } else if (typeof value === "function") {
  224. this.__expect(e instanceof value);
  225. } else if (typeof value === "object") {
  226. this.__expect(e.message === value.message);
  227. }
  228. }
  229. this.__expect(threw);
  230. });
  231. }
  232. pass(message) {
  233. // FIXME: This does nothing. If we want to implement things
  234. // like assertion count, this will have to do something
  235. }
  236. // jest-extended
  237. fail(message) {
  238. this.__doMatcher(() => {
  239. this.__expect(false, message);
  240. });
  241. }
  242. // jest-extended
  243. toThrowWithMessage(class_, message) {
  244. this.__expect(typeof this.target === "function");
  245. this.__expect(class_ !== undefined);
  246. this.__expect(message !== undefined);
  247. this.__doMatcher(() => {
  248. try {
  249. this.target();
  250. this.__expect(false);
  251. } catch (e) {
  252. this.__expect(
  253. e instanceof class_,
  254. () =>
  255. `toThrowWithMessage: expected error to be instance of ${
  256. class_.name
  257. }, got ${String(e.name)}`
  258. );
  259. this.__expect(
  260. e.message.includes(message),
  261. () =>
  262. `toThrowWithMessage: expected error message to include _${String(
  263. message
  264. )}_, got _${String(e.message)}_`
  265. );
  266. }
  267. });
  268. }
  269. // Test for syntax errors; target must be a string
  270. toEval() {
  271. this.__expect(typeof this.target === "string");
  272. const success = canParseSource(this.target);
  273. this.__expect(this.inverted ? !success : success);
  274. }
  275. // Must compile regardless of inverted-ness
  276. toEvalTo(value) {
  277. this.__expect(typeof this.target === "string");
  278. let result;
  279. try {
  280. result = new Function(this.target)();
  281. } catch (e) {
  282. throw new ExpectationError();
  283. }
  284. this.__doMatcher(() => {
  285. this.__expect(deepEquals(value, result));
  286. });
  287. }
  288. toHaveConfigurableProperty(property) {
  289. this.__expect(this.target !== undefined && this.target !== null);
  290. let d = Object.getOwnPropertyDescriptor(this.target, property);
  291. this.__expect(d !== undefined);
  292. this.__doMatcher(() => {
  293. this.__expect(d.configurable);
  294. });
  295. }
  296. toHaveEnumerableProperty(property) {
  297. this.__expect(this.target !== undefined && this.target !== null);
  298. let d = Object.getOwnPropertyDescriptor(this.target, property);
  299. this.__expect(d !== undefined);
  300. this.__doMatcher(() => {
  301. this.__expect(d.enumerable);
  302. });
  303. }
  304. toHaveWritableProperty(property) {
  305. this.__expect(this.target !== undefined && this.target !== null);
  306. let d = Object.getOwnPropertyDescriptor(this.target, property);
  307. this.__expect(d !== undefined);
  308. this.__doMatcher(() => {
  309. this.__expect(d.writable);
  310. });
  311. }
  312. toHaveValueProperty(property, value) {
  313. this.__expect(this.target !== undefined && this.target !== null);
  314. let d = Object.getOwnPropertyDescriptor(this.target, property);
  315. this.__expect(d !== undefined);
  316. this.__doMatcher(() => {
  317. this.__expect(d.value !== undefined);
  318. if (value !== undefined) this.__expect(deepEquals(value, d.value));
  319. });
  320. }
  321. toHaveGetterProperty(property) {
  322. this.__expect(this.target !== undefined && this.target !== null);
  323. let d = Object.getOwnPropertyDescriptor(this.target, property);
  324. this.__expect(d !== undefined);
  325. this.__doMatcher(() => {
  326. this.__expect(d.get !== undefined);
  327. });
  328. }
  329. toHaveSetterProperty(property) {
  330. this.__expect(this.target !== undefined && this.target !== null);
  331. let d = Object.getOwnPropertyDescriptor(this.target, property);
  332. this.__expect(d !== undefined);
  333. this.__doMatcher(() => {
  334. this.__expect(d.set !== undefined);
  335. });
  336. }
  337. __doMatcher(matcher) {
  338. if (!this.inverted) {
  339. matcher();
  340. } else {
  341. let threw = false;
  342. try {
  343. matcher();
  344. } catch (e) {
  345. if (e.name === "ExpectationError") threw = true;
  346. }
  347. if (!threw) throw new ExpectationError("not: test didn't fail");
  348. }
  349. }
  350. __expect(value, details) {
  351. if (value !== true) {
  352. if (details !== undefined) {
  353. throw new ExpectationError(details());
  354. } else {
  355. throw new ExpectationError();
  356. }
  357. }
  358. }
  359. }
  360. expect = value => new Expector(value);
  361. // describe is able to lump test results inside of it by using this context
  362. // variable. Top level tests have the default suite message
  363. const defaultSuiteMessage = "__$$TOP_LEVEL$$__";
  364. let suiteMessage = defaultSuiteMessage;
  365. describe = (message, callback) => {
  366. suiteMessage = message;
  367. callback();
  368. suiteMessage = defaultSuiteMessage;
  369. };
  370. test = (message, callback) => {
  371. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  372. const suite = __TestResults__[suiteMessage];
  373. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  374. suite[message] = {
  375. result: "fail",
  376. details: "Another test with the same message did already run",
  377. };
  378. return;
  379. }
  380. try {
  381. callback();
  382. suite[message] = {
  383. result: "pass",
  384. };
  385. } catch (e) {
  386. suite[message] = {
  387. result: "fail",
  388. details: String(e),
  389. };
  390. }
  391. };
  392. test.skip = (message, callback) => {
  393. if (typeof callback !== "function")
  394. throw new Error("test.skip has invalid second argument (must be a function)");
  395. if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
  396. const suite = __TestResults__[suiteMessage];
  397. if (Object.prototype.hasOwnProperty.call(suite, message)) {
  398. suite[message] = {
  399. result: "fail",
  400. details: "Another test with the same message did already run",
  401. };
  402. return;
  403. }
  404. suite[message] = {
  405. result: "skip",
  406. };
  407. };
  408. })();