import { test, expect } from 'vitest'; import schema from 'json-schema-shorthand'; import u from 'updeep'; import { action } from './actions.js'; import { Updux, dux } from './Updux.js'; test('set a mutation', () => { const dux = new Updux({ initial: { x: 'potato', }, actions: { foo: action('foo', (x) => ({ x })), bar: action('bar'), }, }); dux.setMutation(dux.actions.foo, (payload, action) => { expect(payload).toEqual({ x: 'hello ' }); expect(action).toEqual(dux.actions.foo('hello ')); return u({ x: payload.x + action.type, }); }); const result = dux.reducer(undefined, dux.actions.foo('hello ')); expect(result).toEqual({ x: 'hello foo', }); }); test('mutation of a subdux', async () => { const bar = dux({ actions: { baz: null, }, }); bar.setMutation('baz', () => (state) => ({ ...state, x: 1 })); const foo = dux({ subduxes: { bar }, }); const store = foo.createStore(); store.dispatch.baz(); expect(store.getState()).toMatchObject({ bar: { x: 1 } }); }); test('strings and generators', async () => { const actionA = action('a'); const foo = dux({ actions: { b: null, a: actionA, }, }); // as a string and defined expect(() => foo.setMutation('a', () => {})).not.toThrow(); // as a generator and defined expect(() => foo.setMutation(actionA, () => {})).not.toThrow(); // as a string, not defined expect(() => foo.setMutation('c', () => {})).toThrow(); foo.setMutation(action('d'), () => {}); expect(foo.actions.d).toBeTypeOf('function'); }); test('splat mutation', () => { const myDux = new Updux({ initial: [], actions: { one: null, two: null }, mutations: { '*': (payload) => (state) => payload ? [...state, payload] : state, }, }); const store = myDux.createStore(); expect(store.getState()).toEqual([]); store.dispatch.one(11); store.dispatch.two(22); expect(store.getState()).toEqual([11, 22]); });