2022-08-28 23:29:31 +00:00
|
|
|
import { test, expect } from 'vitest';
|
|
|
|
|
|
|
|
import u from 'updeep';
|
2022-08-29 14:57:59 +00:00
|
|
|
import { action, Updux, dux } from '../src/index.js';
|
2022-08-28 23:29:31 +00:00
|
|
|
|
|
|
|
const addTodoWithId = action('addTodoWithId');
|
|
|
|
const incNextId = action('incNextId');
|
|
|
|
const addTodo = action('addTodo');
|
|
|
|
|
|
|
|
const addTodoEffect = ({ getState, dispatch }) => next => action => {
|
|
|
|
const id = getState.nextId();
|
|
|
|
|
|
|
|
dispatch.incNextId();
|
|
|
|
|
|
|
|
next(action);
|
|
|
|
|
|
|
|
dispatch.addTodoWithId({ description: action.payload, id });
|
|
|
|
}
|
|
|
|
|
|
|
|
const todosDux = new Updux({
|
|
|
|
initial: { nextId: 1, todos: [] },
|
|
|
|
actions: { addTodo, incNextId, addTodoWithId },
|
|
|
|
selectors: {
|
|
|
|
nextId: ({nextId}) => nextId,
|
|
|
|
},
|
|
|
|
mutations: {
|
|
|
|
addTodoWithId: (todo) => u({ todos: (todos) => [...todos, todo] }),
|
|
|
|
incNextId: () => u({ nextId: id => id+1 }),
|
|
|
|
},
|
|
|
|
effects: {
|
|
|
|
'addTodo': addTodoEffect
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
const store = todosDux.createStore();
|
|
|
|
|
|
|
|
test( "tutorial example", async () => {
|
|
|
|
store.dispatch.addTodo('Do the thing');
|
|
|
|
|
|
|
|
expect( store.getState() ).toMatchObject({
|
2022-08-29 14:32:52 +00:00
|
|
|
nextId:2, todos: [ { description: 'Do the thing', id: 1 } ]
|
2022-08-28 23:29:31 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
});
|
2022-08-29 14:57:59 +00:00
|
|
|
|
|
|
|
test( "catch-all effect", () => {
|
|
|
|
|
|
|
|
let seen = [];
|
|
|
|
|
|
|
|
const foo = new Updux({
|
|
|
|
actions: {
|
|
|
|
one: null,
|
|
|
|
two: null,
|
|
|
|
},
|
|
|
|
effects: {
|
|
|
|
'*': (api) => next => action => {
|
|
|
|
seen.push(action.type);
|
|
|
|
next(action);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} );
|
|
|
|
|
|
|
|
const store = foo.createStore();
|
|
|
|
|
|
|
|
store.dispatch.one();
|
|
|
|
store.dispatch.two();
|
|
|
|
|
|
|
|
expect(seen).toEqual([ 'one', 'two' ]);
|
|
|
|
} )
|