1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
|
var describe;
var test;
var expect;
// Stores the results of each test and suite. Has a terrible
// name to avoid name collision.
var __TestResults__ = {};
// So test names like "toString" don't automatically produce an error
Object.setPrototypeOf(__TestResults__, null);
// This array is used to communicate with the C++ program. It treats
// each message in this array as a separate message. Has a terrible
// name to avoid name collision.
var __UserOutput__ = [];
// We also rebind console.log here to use the array above
console.log = (...args) => {
__UserOutput__.push(args.join(" "));
};
class ExpectationError extends Error {
constructor(message) {
super(message);
this.name = "ExpectationError";
}
}
// Use an IIFE to avoid polluting the global namespace as much as possible
(() => {
// FIXME: This is a very naive deepEquals algorithm
const deepEquals = (a, b) => {
if (Array.isArray(a)) return Array.isArray(b) && deepArrayEquals(a, b);
if (typeof a === "object") return typeof b === "object" && deepObjectEquals(a, b);
return Object.is(a, b);
};
const deepArrayEquals = (a, b) => {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; ++i) {
if (!deepEquals(a[i], b[i])) return false;
}
return true;
};
const deepObjectEquals = (a, b) => {
if (a === null) return b === null;
for (let key of Reflect.ownKeys(a)) {
if (!deepEquals(a[key], b[key])) return false;
}
return true;
};
const valueToString = value => {
try {
if (value === 0 && 1 / value < 0) {
return "-0";
}
return String(value);
} catch {
// e.g for objects without a prototype, the above throws.
return Object.prototype.toString.call(value);
}
};
class Expector {
constructor(target, inverted) {
this.target = target;
this.inverted = !!inverted;
}
get not() {
return new Expector(this.target, !this.inverted);
}
toBe(value) {
this.__doMatcher(() => {
this.__expect(
Object.is(this.target, value),
() =>
`toBe: expected _${valueToString(value)}_, got _${valueToString(
this.target
)}_`
);
});
}
// FIXME: Take a precision argument like jest's toBeCloseTo matcher
toBeCloseTo(value) {
this.__expect(
typeof this.target === "number",
() => `toBeCloseTo: expected target of type number, got ${typeof value}`
);
this.__expect(
typeof value === "number",
() => `toBeCloseTo: expected argument of type number, got ${typeof value}`
);
this.__doMatcher(() => {
this.__expect(Math.abs(this.target - value) < 0.000001);
});
}
toHaveLength(length) {
this.__expect(
typeof this.target.length === "number",
() => "toHaveLength: target.length not of type number"
);
this.__doMatcher(() => {
this.__expect(Object.is(this.target.length, length));
});
}
toHaveSize(size) {
this.__expect(
typeof this.target.size === "number",
() => "toHaveSize: target.size not of type number"
);
this.__doMatcher(() => {
this.__expect(Object.is(this.target.size, size));
});
}
toHaveProperty(property, value) {
this.__doMatcher(() => {
let object = this.target;
if (typeof property === "string" && property.includes(".")) {
let propertyArray = [];
while (property.includes(".")) {
let index = property.indexOf(".");
propertyArray.push(property.substring(0, index));
if (index + 1 >= property.length) break;
property = property.substring(index + 1, property.length);
}
propertyArray.push(property);
property = propertyArray;
}
if (Array.isArray(property)) {
for (let key of property) {
this.__expect(object !== undefined && object !== null);
object = object[key];
}
} else {
object = object[property];
}
this.__expect(object !== undefined);
if (value !== undefined) this.__expect(deepEquals(object, value));
});
}
toBeDefined() {
this.__doMatcher(() => {
this.__expect(
this.target !== undefined,
() => "toBeDefined: expected target to be defined, got undefined"
);
});
}
toBeInstanceOf(class_) {
this.__doMatcher(() => {
this.__expect(this.target instanceof class_);
});
}
toBeNull() {
this.__doMatcher(() => {
this.__expect(this.target === null);
});
}
toBeUndefined() {
this.__doMatcher(() => {
this.__expect(
this.target === undefined,
() =>
`toBeUndefined: expected target to be undefined, got _${valueToString(
this.target
)}_`
);
});
}
toBeNaN() {
this.__doMatcher(() => {
this.__expect(
isNaN(this.target),
() => `toBeNaN: expected target to be NaN, got _${valueToString(this.target)}_`
);
});
}
toBeTrue() {
this.__doMatcher(() => {
this.__expect(
this.target === true,
() =>
`toBeTrue: expected target to be true, got _${valueToString(this.target)}_`
);
});
}
toBeFalse() {
this.__doMatcher(() => {
this.__expect(
this.target === false,
() =>
`toBeFalse: expected target to be false, got _${valueToString(
this.target
)}_`
);
});
}
__validateNumericComparisonTypes(value) {
this.__expect(typeof this.target === "number" || typeof this.target === "bigint");
this.__expect(typeof value === "number" || typeof value === "bigint");
this.__expect(typeof this.target === typeof value);
}
toBeLessThan(value) {
this.__validateNumericComparisonTypes(value);
this.__doMatcher(() => {
this.__expect(this.target < value);
});
}
toBeLessThanOrEqual(value) {
this.__validateNumericComparisonTypes(value);
this.__doMatcher(() => {
this.__expect(this.target <= value);
});
}
toBeGreaterThan(value) {
this.__validateNumericComparisonTypes(value);
this.__doMatcher(() => {
this.__expect(this.target > value);
});
}
toBeGreaterThanOrEqual(value) {
this.__validateNumericComparisonTypes(value);
this.__doMatcher(() => {
this.__expect(this.target >= value);
});
}
toContain(item) {
this.__doMatcher(() => {
for (let element of this.target) {
if (item === element) return;
}
throw new ExpectationError();
});
}
toContainEqual(item) {
this.__doMatcher(() => {
for (let element of this.target) {
if (deepEquals(item, element)) return;
}
throw new ExpectationError();
});
}
toEqual(value) {
this.__doMatcher(() => {
this.__expect(
deepEquals(this.target, value),
() =>
`Expected _${valueToString(value)}_, but got _${valueToString(
this.target
)}_`
);
});
}
toThrow(value) {
this.__expect(typeof this.target === "function");
this.__expect(
typeof value === "string" ||
typeof value === "function" ||
typeof value === "object" ||
value === undefined
);
this.__doMatcher(() => {
let threw = true;
try {
this.target();
threw = false;
} catch (e) {
if (typeof value === "string") {
this.__expect(e.message.includes(value));
} else if (typeof value === "function") {
this.__expect(e instanceof value);
} else if (typeof value === "object") {
this.__expect(e.message === value.message);
}
}
this.__expect(threw);
});
}
pass(message) {
// FIXME: This does nothing. If we want to implement things
// like assertion count, this will have to do something
}
// jest-extended
fail(message) {
this.__doMatcher(() => {
this.__expect(false, message);
});
}
// jest-extended
toThrowWithMessage(class_, message) {
this.__expect(typeof this.target === "function");
this.__expect(class_ !== undefined);
this.__expect(message !== undefined);
this.__doMatcher(() => {
try {
this.target();
this.__expect(false, () => "toThrowWithMessage: target function did not throw");
} catch (e) {
this.__expect(
e instanceof class_,
() =>
`toThrowWithMessage: expected error to be instance of ${valueToString(
class_.name
)}, got ${valueToString(e.name)}`
);
this.__expect(
e.message.includes(message),
() =>
`toThrowWithMessage: expected error message to include _${valueToString(
message
)}_, got _${valueToString(e.message)}_`
);
}
});
}
// Test for syntax errors; target must be a string
toEval() {
this.__expect(typeof this.target === "string");
const success = canParseSource(this.target);
this.__expect(
this.inverted ? !success : success,
() =>
`Expected _${valueToString(this.target)}_` +
(this.inverted ? "not to eval but it did" : "to eval but it didn't")
);
}
// Must compile regardless of inverted-ness
toEvalTo(value) {
this.__expect(typeof this.target === "string");
let result;
try {
result = eval(this.target);
} catch (e) {
throw new ExpectationError(
`Expected _${valueToString(this.target)}_ to eval but it failed with ${e}`
);
}
this.__doMatcher(() => {
this.__expect(
deepEquals(value, result),
() =>
`Expected _${valueToString(this.target)}_ to eval to ` +
`_${valueToString(value)}_ but got _${valueToString(result)}_`
);
});
}
toHaveConfigurableProperty(property) {
this.__expect(this.target !== undefined && this.target !== null);
let d = Object.getOwnPropertyDescriptor(this.target, property);
this.__expect(d !== undefined);
this.__doMatcher(() => {
this.__expect(d.configurable);
});
}
toHaveEnumerableProperty(property) {
this.__expect(this.target !== undefined && this.target !== null);
let d = Object.getOwnPropertyDescriptor(this.target, property);
this.__expect(d !== undefined);
this.__doMatcher(() => {
this.__expect(d.enumerable);
});
}
toHaveWritableProperty(property) {
this.__expect(this.target !== undefined && this.target !== null);
let d = Object.getOwnPropertyDescriptor(this.target, property);
this.__expect(d !== undefined);
this.__doMatcher(() => {
this.__expect(d.writable);
});
}
toHaveValueProperty(property, value) {
this.__expect(this.target !== undefined && this.target !== null);
let d = Object.getOwnPropertyDescriptor(this.target, property);
this.__expect(d !== undefined);
this.__doMatcher(() => {
this.__expect(d.value !== undefined);
if (value !== undefined) this.__expect(deepEquals(value, d.value));
});
}
toHaveGetterProperty(property) {
this.__expect(this.target !== undefined && this.target !== null);
let d = Object.getOwnPropertyDescriptor(this.target, property);
this.__expect(d !== undefined);
this.__doMatcher(() => {
this.__expect(d.get !== undefined);
});
}
toHaveSetterProperty(property) {
this.__expect(this.target !== undefined && this.target !== null);
let d = Object.getOwnPropertyDescriptor(this.target, property);
this.__expect(d !== undefined);
this.__doMatcher(() => {
this.__expect(d.set !== undefined);
});
}
toBeIteratorResultWithValue(value) {
this.__expect(this.target !== undefined && this.target !== null);
this.__doMatcher(() => {
this.__expect(
this.target.done === false,
() =>
`toGiveIteratorResultWithValue: expected 'done' to be _false_ got ${valueToString(
this.target.done
)}`
);
this.__expect(
deepEquals(value, this.target.value),
() =>
`toGiveIteratorResultWithValue: expected 'value' to be _${valueToString(
value
)}_ got ${valueToString(this.target.value)}`
);
});
}
toBeIteratorResultDone() {
this.__expect(this.target !== undefined && this.target !== null);
this.__doMatcher(() => {
this.__expect(
this.target.done === true,
() =>
`toGiveIteratorResultDone: expected 'done' to be _true_ got ${valueToString(
this.target.done
)}`
);
this.__expect(
this.target.value === undefined,
() =>
`toGiveIteratorResultDone: expected 'value' to be _undefined_ got ${valueToString(
this.target.value
)}`
);
});
}
__doMatcher(matcher) {
if (!this.inverted) {
matcher();
} else {
let threw = false;
try {
matcher();
} catch (e) {
if (e.name === "ExpectationError") threw = true;
}
if (!threw) throw new ExpectationError("not: test didn't fail");
}
}
__expect(value, details) {
if (value !== true) {
if (details !== undefined) {
if (details instanceof Function) throw new ExpectationError(details());
else throw new ExpectationError(details);
} else {
throw new ExpectationError();
}
}
}
}
expect = value => new Expector(value);
// describe is able to lump test results inside of it by using this context
// variable. Top level tests have the default suite message
const defaultSuiteMessage = "__$$TOP_LEVEL$$__";
let suiteMessage = defaultSuiteMessage;
describe = (message, callback) => {
suiteMessage = message;
if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
try {
callback();
} catch (e) {
__TestResults__[suiteMessage][defaultSuiteMessage] = {
result: "fail",
details: String(e),
duration: 0,
};
}
suiteMessage = defaultSuiteMessage;
};
test = (message, callback) => {
if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
const suite = __TestResults__[suiteMessage];
if (Object.prototype.hasOwnProperty.call(suite, message)) {
suite[message] = {
result: "fail",
details: "Another test with the same message did already run",
duration: 0,
};
return;
}
const now = () => Temporal.Now.instant().epochNanoseconds;
const start = now();
const time_us = () => Number(BigInt.asIntN(53, (now() - start) / 1000n));
try {
callback();
suite[message] = {
result: "pass",
duration: time_us(),
};
} catch (e) {
suite[message] = {
result: "fail",
details: String(e),
duration: time_us(),
};
}
};
test.skip = (message, callback) => {
if (typeof callback !== "function")
throw new Error("test.skip has invalid second argument (must be a function)");
if (!__TestResults__[suiteMessage]) __TestResults__[suiteMessage] = {};
const suite = __TestResults__[suiteMessage];
if (Object.prototype.hasOwnProperty.call(suite, message)) {
suite[message] = {
result: "fail",
details: "Another test with the same message did already run",
duration: 0,
};
return;
}
suite[message] = {
result: "skip",
duration: 0,
};
};
})();
|