relu-core
Version:
108 lines (107 loc) • 2.74 kB
JavaScript
var should = require("should");
var rp = require("../");
var checkRefs = require("./checkRefs");
describe("computed", function() {
it("should compute the value (very simple)", checkRefs(function() {
var x = rp.variable("test");
var counter = 0;
var y = rp.computed(function() {
return x() + (++counter);
});
y().should.be.eql("test1");
}));
it("should compute the value", checkRefs(function() {
var x = rp.variable("test");
var counter = 0;
var y = rp.computed(function() {
return x() + (++counter);
});
y.isWritable().should.be.eql(false);
y().should.be.eql("test1");
y().should.be.eql("test1");
x.set("TEST");
y().should.be.eql("TEST2");
x.set("A");
x.set("B");
y().should.be.eql("B4");
rp.atomic(function() {
x.set("C");
x.set("D");
})
y().should.be.eql("D5");
}));
it("should compute the value from a computed value", checkRefs(function() {
var x1 = rp.variable("aa");
var x2 = rp.variable("bb");
var counter1 = 0;
var counter2 = 0;
var counter3 = 0;
var y1 = x1.computed(function(x) {
return x + (++counter1);
}).scope();
var y2 = rp.computed(function() {
return x2() + (++counter2);
});
var z = rp.computed(function() {
return y1() + y2() + "z" + (++counter3);
});
z().should.be.eql("aa1bb1z1");
x1.add("a");
x2.add("b");
z().should.be.eql("aaa2bbb2z3");
rp.atomic(function() {
x1.add("A");
x2.add("B");
});
z().should.be.eql("aaaA3bbbB3z4");
}));
it("should summarize changes in atomic", checkRefs(function() {
var x = rp.variable({
a: 1,
b: 2
});
var y = rp.variable(3);
var counter = 0;
var z = rp.computed(function() {
return x().a + "," + x("b")() + "," + y() + "," + (++counter);
});
z().should.be.eql("1,2,3,1");
rp.atomic(function() {
x.set({
a: 10,
b: 20
});
x("a").set(11);
x("b").set(22);
y.set(32);
y.set(33);
});
z().should.be.eql("11,22,33,2");
}));
it("should fire correct events", checkRefs(function() {
var y = rp.variable(1);
var x = y.plus("test");
var events = [];
x.onChanged(function() {
events.push("changed");
});
x.onUpdated(function(n, o) {
events.push(["updated", n, o]);
});
x.onAdded(function(idx, i) {
events.push(["added", idx, i]);
});
x.onRemoved(function(idx, i) {
events.push(["removed", idx, i]);
});
y.set(2);
events.shift().should.be.eql(["updated", "2test", "1test"]);
events.shift().should.be.eql("changed");
rp.atomic(function() {
y.set(3);
y.set(4);
});
events.shift().should.be.eql(["updated", "4test", "2test"]);
events.shift().should.be.eql("changed");
}));
});