updux/src/reactions.test.ts

83 lines
2.1 KiB
TypeScript

import { test, expect, vi } from 'vitest';
import Updux from './index.js';
test('basic reactions', () => {
const foo = new Updux({
initialState: 0,
actions: { inc: 0, reset: 0 },
});
// TODO immer that stuff
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: 0, reset: 0 },
selectors: {
getIt: (x) => x,
},
});
const foo = new Updux({ actions: { notInBar: 0 }, subduxes: { bar } });
// TODO immer that stuff
bar.addMutation(foo.actions.inc, () => (state) => state + 1);
bar.addMutation(foo.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 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();
store.dispatch.inc();
expect(store.getState.getIt()).toEqual(0); // we've been reset
store.dispatch.inc();
store.dispatch.inc();
store.dispatch.inc();
store.dispatch.inc();
expect(store.getState.getIt()).toEqual(4); // we've unsubscribed
});