import { test, expect } from 'vitest'; import Updux from './index.js'; test('basic reactions', () => { const foo = new Updux({ initialState: 0, actions: { inc: null, reset: null }, }); foo.addMutation(foo.actions.inc, () => (state) => state + 1); foo.addMutation(foo.actions.reset, () => (state) => 0); foo.addReaction((api) => (state, _previous, unsubscribe) => { if (state < 3) return; unsubscribe(); api.dispatch.reset(); }); // TODO //reaction: (api) => (state,previous,unsubscribe) const store = foo.createStore(); store.dispatch.inc(); expect(store.getState()).toEqual(1); store.dispatch.inc(); store.dispatch.inc(); expect(store.getState()).toEqual(0); // we've been reset store.dispatch.inc(); store.dispatch.inc(); store.dispatch.inc(); store.dispatch.inc(); expect(store.getState()).toEqual(4); // we've unsubscribed }); test('subdux reactions', () => { const bar = new Updux({ initialState: 0, actions: { inc: null, reset: null }, selectors: { getIt: (x) => x, }, }); bar.addMutation(bar.actions.inc, () => (state) => { return state + 1; }); bar.addMutation(bar.actions.reset, () => (state) => 0); let seen = 0; bar.addReaction((api) => (state, _previous, unsubscribe) => { seen++; expect(api.actions).not.toHaveProperty('notInBar'); expect(state).toBeTypeOf('number'); if (state < 3) return; unsubscribe(); api.dispatch.reset(); }); const foo = new Updux({ actions: { notInBar: null }, subduxes: { bar }, }); const store = foo.createStore(); store.dispatch.inc(); expect(seen).toEqual(1); expect(store.getState()).toEqual({ bar: 1 }); expect(store.getState.getIt()).toEqual(1); store.dispatch.inc(); expect(seen).toEqual(2); store.dispatch.inc(); expect(seen).toEqual(3); expect(store.getState.getIt()).toEqual(0); // we've been reset store.dispatch.inc(); store.dispatch.inc(); store.dispatch.inc(); store.dispatch.inc(); expect(seen).toEqual(3); expect(store.getState.getIt()).toEqual(4); // we've unsubscribed });