test store push

This commit is contained in:
Radek Stepan 2016-01-26 18:51:10 +01:00
parent 208d2f2cea
commit 55654f762f
2 changed files with 37 additions and 13 deletions

View File

@ -45,9 +45,9 @@ export default class Store extends EventEmitter {
// Set a value on a key. Pass falsy value as 3rd param to not emit changes.
set(...args) {
if (args.length == 1) {
var val = args[0];
var val = args[0]; // keep var!
} else {
var [ key, val, emit=true ] = args;
var [ key, val, emit=true ] = args; // keep var!
}
// A list of changes.
@ -76,12 +76,14 @@ export default class Store extends EventEmitter {
});
}
// TODO: Unit-test.
// Push a value on an array or init it.
push(key, val) {
// Make sure the key is an array.
if (!_.isArray(key)) key = key.split('.');
let obj = this.get(key);
if (_.isArray(obj)) {
// TODO: Don't assume a string.
this.set(`${key}.${obj.length}`, val); // TODO: won't emit for root key
this.set(key.concat(obj.length), val); // TODO: won't emit for root key
return obj.length - 1;
} else {
this.set(key, [ val ]);

View File

@ -7,9 +7,31 @@ export default {
'store - set': (done) => {
let s = new Store();
s.set('A.B', 1);
s.set('A.B', 1); // key as a string
s.set([ 'A', 'C' ], 2); // key as an array
assert.deepEqual({ A: { B: 1 }}, s.get());
assert.deepEqual({ A: { B: 1, C: 2 }}, s.get());
done();
},
'store - push': (done) => {
let s = new Store({ 'list': [ 'A' ] });
s.push('list', 'B'); // key as a string
s.push([ 'list' ], 'C'); // key as an array
assert.deepEqual({ 'list': [ 'A', 'B', 'C' ] }, s.get());
done();
},
'store - push with init': (done) => {
let s = new Store();
s.push('list', 'A');
assert.deepEqual({ 'list': [ 'A' ] }, s.get());
done();
},
@ -62,11 +84,11 @@ export default {
let called = false;
let cb = s.cb(() => called = true);
assert.equal(Object.keys(s._cbs).length, 1);
assert.equal(1, Object.keys(s._cbs).length);
cb();
assert.ok(called);
assert.equal(Object.keys(s._cbs).length, 0);
assert.deepEqual(events, [ true, false ]);
assert.equal(0, Object.keys(s._cbs).length);
assert.deepEqual([ true, false ], events);
done();
},
@ -79,14 +101,14 @@ export default {
let called = false;
let cb = s.cb(() => called = true);
assert.equal(Object.keys(s._cbs).length, 1);
assert.equal(1, Object.keys(s._cbs).length);
setTimeout(cb, 10);
s.clean();
assert.equal(Object.keys(s._cbs).length, 0);
assert.equal(0, Object.keys(s._cbs).length);
setTimeout(() => {
assert.ok(!called);
assert.deepEqual(events, [ true, false ]);
assert.deepEqual([ true, false ], events);
done();
}, 20);
}