updux/dist/tutorial/actions.test.js

71 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2025-01-31 18:16:41 +00:00
import { test, expect } from 'vitest';
/// --8<-- [start:actions1]
import Updux, { createAction, withPayload } from 'updux';
const addTodo = createAction('addTodo', withPayload());
const todoDone = createAction('todoDone', withPayload());
/// --8<-- [end:actions1]
test('createAction', () => {
expect(addTodo).toBeTypeOf('function');
expect(todoDone).toBeTypeOf('function');
});
const todosDux = new Updux({
initialState: {
nextId: 1,
todos: [],
},
actions: {
addTodo,
todoDone,
},
});
/// --8<-- [start:actions2]
todosDux.actions.addTodo('write tutorial');
// { type: 'addTodo', payload: 'write tutorial' }
/// --8<-- [end:actions2]
test('basic', () => {
expect(todosDux.actions.addTodo('write tutorial')).toEqual({
type: 'addTodo',
payload: 'write tutorial',
});
});
/// --8<-- [start:addMutation-1]
todosDux.addMutation(addTodo, (description) => ({ todos, nextId }) => ({
nextId: 1 + nextId,
todos: todos.concat({ description, id: nextId, done: false }),
}));
todosDux.addMutation(todoDone, (id) => ({ todos, nextId }) => ({
nextId: 1 + nextId,
todos: todos.map((todo) => {
if (todo.id !== id)
return todo;
return Object.assign(Object.assign({}, todo), { done: true });
}),
}));
/// --8<-- [end:addMutation-1]
const store = todosDux.createStore();
store.dispatch.addTodo('write tutorial');
const state = store.getState();
// {
// nextId: 2,
// todos: [
// {
// description: 'write tutorial',
// done: false,
// id: 1,
// }
// ]
// }
/// --8<-- [end:addMutation]
test('addMutation', () => {
expect(state).toEqual({
nextId: 2,
todos: [
{
description: 'write tutorial',
done: false,
id: 1,
},
],
});
});