updux/dist/tutorial/monolith.test.js

55 lines
1.7 KiB
JavaScript
Raw Normal View History

2025-01-31 18:16:41 +00:00
import { test, expect } from 'vitest';
/// --8<-- [start:mono]
import Updux from '../index.js';
import u from '@yanick/updeep-remeda';
const todosDux = new Updux({
initialState: {
nextId: 1,
todos: [],
},
actions: {
addTodo: (description) => description,
addTodoWithId: (description, id) => ({
description,
id,
done: false,
}),
todoDone: (id) => id,
incNextId: () => { },
},
selectors: {
getTodoById: ({ todos }) => (id) => todos.find(u.matches({ id })),
getNextId: ({ nextId }) => nextId,
},
})
.addMutation('addTodoWithId', (todo) => u.updateIn('todos', (todos) => [...todos, todo]))
.addMutation('incNextId', () => u({ nextId: (x) => x + 1 }))
.addMutation('todoDone', (id) => u.updateIn('todos', u.map(u.if(u.matches({ id }), { done: true }))))
.addEffect('addTodo', ({ getState, dispatch }) => (next) => (action) => {
const id = getState.getNextId();
dispatch.incNextId();
next(action);
dispatch.addTodoWithId(action.payload, id);
});
/// --8<-- [end:mono]
test('basic', () => {
const store = todosDux.createStore();
store.dispatch.addTodo('write tutorial');
store.dispatch.addTodo('have fun');
expect(store.getState()).toMatchObject({
nextId: 3,
todos: [
{ id: 1, description: 'write tutorial', done: false },
{ id: 2, description: 'have fun', done: false },
],
});
store.dispatch.todoDone(1);
expect(store.getState()).toMatchObject({
nextId: 3,
todos: [
{ id: 1, description: 'write tutorial', done: true },
{ id: 2, description: 'have fun', done: false },
],
});
});