Skip to content

Commit

Permalink
feature(hooks): log initial state (#69)
Browse files Browse the repository at this point in the history
  • Loading branch information
yoshuawuyts committed Jan 10, 2017
1 parent f5d6805 commit d57d69a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ function dispatcher (hooks) {
// state rather than indvidual chunks, so we apply it outside the loop
if (!stateCalled && opts.state !== false) {
_state = wrapHook(_state, initialStateWraps)
if (onStateChangeHooks.length) {
applyHook(onStateChangeHooks, _state, {}, {}, 'init', createSend)
}
}

if (!opts.noSubscriptions) subsCalled = true
Expand Down
40 changes: 29 additions & 11 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -490,13 +490,19 @@ tape('handlers: subscriptions', (t) => {

tape('hooks: onStateChange', (t) => {
t.test('should be called whenever state changes', (t) => {
t.plan(4)
t.plan(5)
var called = false
const store = barracks({
onStateChange: (state, data, prev, caller, createSend) => {
t.deepEqual(data, { count: 3 }, 'action is equal')
t.deepEqual(state, { count: 4 }, 'state is equal')
t.deepEqual(prev, { count: 1 }, 'prev is equal')
t.equal(caller, 'increment', 'caller is equal')
if (!called) {
t.deepEqual(state, { count: 1 }, 'state is equal on first try')
called = true
} else {
t.deepEqual(data, { count: 3 }, 'action is equal')
t.deepEqual(state, { count: 4 }, 'state is equal')
t.deepEqual(prev, { count: 1 }, 'prev is equal')
t.equal(caller, 'increment', 'caller is equal')
}
}
})

Expand All @@ -513,12 +519,19 @@ tape('hooks: onStateChange', (t) => {
})

t.test('should allow triggering other actions', (t) => {
t.plan(2)
t.plan(4)
var called = false
const store = barracks({
onStateChange: function (state, data, prev, caller, createSend) {
t.pass('onStateChange called')
const send = createSend('test:onStateChange', true)
send('foo')
if (!called) {
t.pass('onStateChange called')
t.equal(caller, 'init', "caller was 'init'")
called = true
} else {
t.pass('onStateChange called')
const send = createSend('test:onStateChange', true)
send('foo')
}
}
})

Expand All @@ -542,10 +555,15 @@ tape('hooks: onStateChange', (t) => {

t.test('previous state should not be mutated', (t) => {
t.plan(2)
var initialized = false
const storeNS = barracks({
onStateChange: (state, data, prev, caller, createSend) => {
t.equal(state.ns.items.length, 3, 'state was updated')
t.equal(prev.ns.items.length, 0, 'prev was left as-is')
if (!initialized) {
initialized = true
} else {
t.equal(state.ns.items.length, 3, 'state was updated')
t.equal(prev.ns.items.length, 0, 'prev was left as-is')
}
}
})

Expand Down

0 comments on commit d57d69a

Please sign in to comment.