updux/src/mutations.test.ts

81 lines
2.0 KiB
TypeScript

import { test, expect } from 'vitest';
import Updux, { createAction } from './index.js';
test('set a mutation', () => {
const dux = new Updux({
initialState: '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({
initialState: '',
});
dux.addMutation(
() => true,
(payload, action) => () => 'got it',
);
expect(dux.reducer(undefined, { type: 'foo' })).toEqual('got it');
});
test('default mutation', () => {
const dux = new Updux({
initialState: '',
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');
});
test('mutation of a subdux', () => {
const baz = createAction('baz');
const noop = createAction('noop');
const stopit = createAction('stopit');
const bar = new Updux({
initialState: 0,
actions: {
baz,
stopit,
},
});
bar.addMutation(baz, () => () => 1);
bar.addMutation(stopit, () => () => 2);
const foo = new Updux({
subduxes: { bar },
});
foo.addMutation(stopit, () => (state) => state, true);
expect(foo.reducer(undefined, noop())).toHaveProperty('bar', 0);
expect(foo.reducer(undefined, baz())).toHaveProperty('bar', 1);
expect(foo.reducer(undefined, stopit())).toHaveProperty('bar', 0);
});