/
test.js
67 lines (57 loc) · 2.56 KB
/
test.js
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
/*--------- START TESTS ---------*/
const assert = require("assert");
const { Subject, Dipatcher } = require("./observational");
const INITIAL_VALUE = "inital value";
const SECOND_VALUE = "second value";
const THIRD_VALUE = "third value";
let subject;
let scopeA;
let scopeB;
test("can create Subject", async () => {
subject = new Subject(INITIAL_VALUE);
assert(typeof subject === "object", "Subject wasn't an object");
assert(typeof subject.listen === "function", "Subject had no listen function");
assert(subject.value === INITIAL_VALUE, "Subject value wasn't inital value");
});
test("can react to Subject", async () => {
const scope = {};
let outerValue = "";
subject.listen(scope, value => outerValue = value);
assert(outerValue === INITIAL_VALUE, "Subject.value did't affect outerValue");
subject.setValue(SECOND_VALUE);
assert(outerValue === SECOND_VALUE, "Subject.setValue didn't set outerValue to " + SECOND_VALUE);
});
test("Subject correctly subscribes", async () => {
scopeA = { value: "", setValue: x => scopeA.value = x };
scopeB = { value: "", setValue: x => scopeB.value = x };
subject = new Subject(INITIAL_VALUE);
subject.listen(scopeA, scopeA.setValue);
subject.listen(scopeB, scopeB.setValue);
assert(scopeA.value === INITIAL_VALUE, "scopeA value wasn't initial value, it was " + scopeA.value);
assert(scopeB.value === INITIAL_VALUE, "scopeB value wasn't initial value, it was " + scopeB.value);
subject.setValue(SECOND_VALUE);
assert(scopeA.value === SECOND_VALUE, "scopeA value isn't second value " + SECOND_VALUE);
assert(scopeB.value === SECOND_VALUE, "scopeB value isn't second value " + SECOND_VALUE);
});
test("Subject correctly unsubscribes", async () => {
subject.unlistenAll(scopeA);
subject.setValue(THIRD_VALUE);
assert(scopeA.value === SECOND_VALUE, "scopeA value isn't second value: " + SECOND_VALUE);
assert(scopeB.value === THIRD_VALUE, "scopeB value isn't third value: " + THIRD_VALUE);
})
/*--------- END TESTS ---------*/
/** run tests - generated by http://npmjs.com/tinit */
function test(text, func) { (test.all = test.all || []).push({ i: test.all.length, text, func }); }
(async () => { // autorun
const log = (msg, c) => process.stdout.write((["\033[32m", "\033[31m"][c] || "") + msg + "\033[0m");
log("tinit running " + test.all.length + " tests...\n");
while ((t = test.all.shift())) {
log(" > " + (t.i + 1) + ". " + t.text + "...");
try { await t.func(); } catch (e) {
log("FAIL\n" + (e && e.stack || e) + "\n", 1);
process.exit(1);
};
log("PASS\n", 0);
}
process.exit(0);
})();