updux/src/subscriptions.test.js

112 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-06-19 23:29:12 +00:00
import tap from 'tap';
import Updux from '.';
2021-05-02 18:35:37 +00:00
import u from '@yanick/updeep';
2020-06-19 23:29:12 +00:00
2021-10-08 19:33:45 +00:00
tap.test( 'subscriptions', async() => {
2020-06-19 23:29:12 +00:00
const inc = action('inc');
2021-10-08 19:33:45 +00:00
const set_copy = action('set_copy');
2020-06-19 23:29:12 +00:00
const dux = new Updux({
initial: {
x: 0,
2021-10-08 19:33:45 +00:00
copy: 0,
2020-06-19 23:29:12 +00:00
},
actions: {
inc,
},
2021-10-08 19:33:45 +00:00
mutations: {
inc: payload => u({ x: x => x + 1 }),
set_copy: copy => u({ copy }),
},
2020-06-19 23:29:12 +00:00
});
dux.addSubscription(store => (state, unsubscribe) => {
if (state.x > 2) return unsubscribe();
2021-10-08 19:33:45 +00:00
store.dispatch(set_copy(state.x));
2020-06-19 23:29:12 +00:00
});
const store = dux.createStore();
store.dispatch(inc());
2021-10-08 19:33:45 +00:00
tap.same(store.getState(), { x: 1, copy: 1 });
2020-06-19 23:29:12 +00:00
store.dispatch(inc());
store.dispatch(inc());
2021-10-08 19:33:45 +00:00
tap.same(store.getState(), { x: 3, copy: 2 }, 'we unsubscribed');
} );
2020-06-19 23:29:12 +00:00
tap.test('subduxes subscriptions', async t => {
const inc_top = action('inc_top');
const inc_bar = action('inc_bar');
2021-10-08 19:33:45 +00:00
const transform_bar = action('transform_bar');
2020-06-19 23:29:12 +00:00
const bar = new Updux({
initial: 'a',
mutations: [
[inc_bar, () => state => state + 'a'],
[transform_bar, outcome => () => outcome],
],
subscriptions: [
store => (state, unsubscribe) => {
console.log({ state });
if (state.length <= 2) return;
unsubscribe();
store.dispatch(transform_bar('look at ' + state));
},
],
});
const dux = new Updux({
initial: {
count: 0,
},
subduxes: {
bar: bar.asDux,
},
mutations: [[inc_top, () => u({ count: count => count + 1 })]],
effects: [
[
'*',
() => next => action => {
console.log('before ', action.type);
next(action);
console.log({ action });
},
],
],
subscriptions: [
store => {
2021-10-08 19:33:45 +00:00
let previous;
2020-06-19 23:29:12 +00:00
return ({ count }) => {
if (count !== previous) {
previous = count;
store.dispatch(inc_bar());
}
};
},
],
});
const store = dux.createStore();
store.dispatch(inc_top());
store.dispatch(inc_top());
t.same(store.getState(), {
count: 2,
bar: 'look at look at aaa',
});
store.dispatch(inc_top());
t.same(store.getState(), {
count: 3,
bar: 'look at look at aaaa',
});
});