2023-03-09 15:41:15 +00:00
|
|
|
import { test, expect } from 'vitest';
|
|
|
|
|
2023-03-09 19:48:11 +00:00
|
|
|
import Updux, { createAction } from './index.js';
|
2023-03-09 15:41:15 +00:00
|
|
|
|
|
|
|
test('set a mutation', () => {
|
|
|
|
const dux = new Updux({
|
|
|
|
initial: 'potato',
|
|
|
|
actions: {
|
|
|
|
foo: (x) => ({ x }),
|
|
|
|
bar: 0,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
let didIt = false;
|
|
|
|
|
|
|
|
dux.addMutation(dux.actions.foo, (payload, action) => () => {
|
|
|
|
didIt = true;
|
|
|
|
expect(payload).toEqual({ x: 'hello ' });
|
|
|
|
expect(action).toEqual(dux.actions.foo('hello '));
|
|
|
|
return payload.x + action.type;
|
|
|
|
});
|
|
|
|
|
|
|
|
const result = dux.reducer(undefined, dux.actions.foo('hello '));
|
|
|
|
expect(didIt).toBeTruthy();
|
|
|
|
expect(result).toEqual('hello foo');
|
|
|
|
});
|
|
|
|
|
|
|
|
test('catch-all mutation', () => {
|
|
|
|
const dux = new Updux({
|
|
|
|
initial: '',
|
|
|
|
});
|
|
|
|
|
|
|
|
dux.addMutation(
|
|
|
|
() => true,
|
|
|
|
(payload, action) => () => 'got it',
|
|
|
|
);
|
|
|
|
|
|
|
|
expect(dux.reducer(undefined, { type: 'foo' })).toEqual('got it');
|
|
|
|
});
|
2023-03-09 15:59:00 +00:00
|
|
|
|
|
|
|
test('default mutation', () => {
|
|
|
|
const dux = new Updux({
|
|
|
|
initial: '',
|
|
|
|
actions: {
|
|
|
|
foo: 0,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
dux.addMutation(dux.actions.foo, () => () => 'got it');
|
|
|
|
|
|
|
|
dux.addDefaultMutation((_payload, action) => () => action.type);
|
|
|
|
|
|
|
|
expect(dux.reducer(undefined, { type: 'foo' })).toEqual('got it');
|
|
|
|
expect(dux.reducer(undefined, { type: 'bar' })).toEqual('bar');
|
|
|
|
});
|
2023-03-09 19:48:11 +00:00
|
|
|
|
|
|
|
test('mutation of a subdux', () => {
|
|
|
|
const baz = createAction('baz');
|
2023-03-09 20:13:13 +00:00
|
|
|
const noop = createAction('noop');
|
|
|
|
const stopit = createAction('stopit');
|
2023-03-09 19:48:11 +00:00
|
|
|
|
|
|
|
const bar = new Updux({
|
|
|
|
initial: 0,
|
|
|
|
actions: {
|
|
|
|
baz,
|
2023-03-09 20:13:13 +00:00
|
|
|
stopit,
|
2023-03-09 19:48:11 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
bar.addMutation(baz, () => () => 1);
|
2023-03-09 20:13:13 +00:00
|
|
|
bar.addMutation(stopit, () => () => 2);
|
2023-03-09 19:48:11 +00:00
|
|
|
|
|
|
|
const foo = new Updux({
|
|
|
|
subduxes: { bar },
|
|
|
|
});
|
2023-03-09 20:13:13 +00:00
|
|
|
foo.addMutation(stopit, () => (state) => state, true);
|
2023-03-09 19:48:11 +00:00
|
|
|
|
2023-03-09 20:13:13 +00:00
|
|
|
expect(foo.reducer(undefined, noop())).toHaveProperty('bar', 0);
|
2023-03-09 19:48:11 +00:00
|
|
|
expect(foo.reducer(undefined, baz())).toHaveProperty('bar', 1);
|
2023-03-09 20:13:13 +00:00
|
|
|
expect(foo.reducer(undefined, stopit())).toHaveProperty('bar', 0);
|
2023-03-09 19:48:11 +00:00
|
|
|
});
|