-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex2.test.js
More file actions
64 lines (50 loc) · 1.55 KB
/
ex2.test.js
File metadata and controls
64 lines (50 loc) · 1.55 KB
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
'use strict';
const { wrapCallable } = require('./ex2');
function assert(condition, message) {
if (!condition) throw new Error(message || 'Assertion failed');
}
{
const events = [];
function addWithBase(a, b) {
return this.base + a + b;
}
const wrapped = wrapCallable(addWithBase, {
before(args) {
events.push(`before:${args.join(',')}`);
},
after(result) {
events.push(`after:${result}`);
},
});
const out = wrapped.call({ base: 10 }, 1, 2);
assert(out === 13, 'Expected call to preserve explicit this binding');
assert(
JSON.stringify(events) === JSON.stringify(['before:1,2', 'after:13']),
'Expected before/after hooks around normal call'
);
}
{
const events = [];
function Person(name) {
this.name = name;
}
Person.prototype.kind = 'person';
const WrappedPerson = wrapCallable(Person, {
before(args) {
events.push(`before-new:${args[0]}`);
},
after(result) {
events.push(`after-new:${result && result.name}`);
},
});
const p = new WrappedPerson('Ada');
assert(p.name === 'Ada', 'Expected constructed instance fields to be initialized');
assert(p.kind === 'person', 'Expected prototype chain to be preserved');
assert(p instanceof Person, 'Expected instance to be Person');
assert(p instanceof WrappedPerson, 'Expected instance to pass wrapped constructor instanceof');
assert(
JSON.stringify(events) === JSON.stringify(['before-new:Ada', 'after-new:Ada']),
'Expected before/after hooks around construction'
);
}
console.log('ex2 tests passed');