80 lines
2.6 KiB
JavaScript
80 lines
2.6 KiB
JavaScript
import { createAction } from '@reduxjs/toolkit';
|
|
import { test, expect } from 'vitest';
|
|
import { withPayload } from './actions.js';
|
|
import { buildReducer } from './reducer.js';
|
|
import Updux from './Updux.js';
|
|
test('buildReducer, initialState state', () => {
|
|
const reducer = buildReducer({ a: 1 });
|
|
expect(reducer(undefined, { type: 'foo' })).toEqual({ a: 1 });
|
|
});
|
|
test('buildReducer, mutation', () => {
|
|
const reducer = buildReducer(1, [
|
|
{
|
|
matcher: ({ type }) => type === 'inc',
|
|
mutation: () => (state) => state + 1,
|
|
terminal: false,
|
|
},
|
|
]);
|
|
expect(reducer(undefined, { type: 'foo' })).toEqual(1);
|
|
expect(reducer(undefined, { type: 'inc' })).toEqual(2);
|
|
});
|
|
test('basic reducer', () => {
|
|
const add = createAction('add', withPayload());
|
|
const dux = new Updux({
|
|
initialState: 12,
|
|
}).addMutation(add, (incr, action) => (state) => {
|
|
expectTypeOf(incr).toMatchTypeOf();
|
|
expectTypeOf(state).toMatchTypeOf();
|
|
expectTypeOf(action).toMatchTypeOf();
|
|
return state + incr;
|
|
});
|
|
expect(dux.reducer).toBeTypeOf('function');
|
|
expect(dux.reducer(1, { type: 'noop' })).toEqual(1); // noop
|
|
expect(dux.reducer(1, dux.actions.add(2))).toEqual(3);
|
|
});
|
|
test('defaultMutation', () => {
|
|
const dux = new Updux({
|
|
initialState: { a: 0, b: 0 },
|
|
actions: {
|
|
add: (x) => x,
|
|
},
|
|
});
|
|
dux.addMutation(dux.actions.add, (incr) => (state) => (Object.assign(Object.assign({}, state), { a: state.a + incr })));
|
|
dux.setDefaultMutation((payload) => (state) => (Object.assign(Object.assign({}, state), { b: state.b + 1 })));
|
|
expect(dux.reducer({ a: 0, b: 0 }, { type: 'noop' })).toMatchObject({
|
|
a: 0,
|
|
b: 1,
|
|
}); // noop catches the default mutation
|
|
expect(dux.reducer({ a: 1, b: 0 }, dux.actions.add(2))).toMatchObject({
|
|
a: 3,
|
|
b: 0,
|
|
});
|
|
});
|
|
test('subduxes mutations', () => {
|
|
const sub1 = new Updux({
|
|
initialState: 0,
|
|
actions: {
|
|
sub1action: null,
|
|
},
|
|
});
|
|
sub1.addMutation(sub1.actions.sub1action, () => (state) => state + 1);
|
|
const dux = new Updux({
|
|
subduxes: {
|
|
sub1,
|
|
},
|
|
});
|
|
expect(dux.reducer(undefined, dux.actions.sub1action())).toMatchObject({
|
|
sub1: 1,
|
|
});
|
|
});
|
|
test('upreducer', () => {
|
|
const dux = new Updux({
|
|
initialState: 0,
|
|
actions: {
|
|
incr: (x) => x,
|
|
},
|
|
}).addMutation('incr', (i) => state => state + i);
|
|
expect(dux.reducer(undefined, dux.actions.incr(5))).toEqual(5);
|
|
expect(dux.upreducer(dux.actions.incr(7))()).toEqual(7);
|
|
});
|