test-common.js 16 KB

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