updux/src/mutations.test.ts

125 lines
3.1 KiB
TypeScript

import { createAction } from '@reduxjs/toolkit';
import { test, expect } from 'vitest';
import { withPayload } from './actions.js';
import Updux from './Updux.js';
test('set a mutation', () => {
const dux = new Updux({
initialState: 'potato',
actions: {
foo: (x: string) => ({ x }),
bar: null,
},
});
let didIt = false;
dux.addMutation(dux.actions.foo, (payload, action) => () => {
expectTypeOf(payload).toMatchTypeOf<{ x: string }>();
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: null,
},
});
dux.addMutation(dux.actions.foo, () => () => 'got it');
dux.setDefaultMutation((_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);
});
test('actionType as string', () => {
const dux = new Updux({
actions: {
doIt: (id: number) => id,
},
});
dux.addMutation('doIt', (payload) => (state) => {
expectTypeOf(payload).toMatchTypeOf<number>();
return state;
});
expect(() => {
// @ts-ignore
dux.addMutation('unknown', () => (x) => x);
}).toThrow();
});
test('setDefaultMutation return value', () => {
const dux = new Updux({
initialState: 13,
});
let withDM = dux.setDefaultMutation(() => (state) => state);
expect(withDM).toEqual(dux);
expectTypeOf(withDM.initialState).toBeNumber();
});
test('addMutation with createAction', () => {
const setName = createAction('setName', withPayload<string>());
const dux = new Updux({
initialState: {
name: '',
round: 1,
},
}).addMutation(setName, (name) => (state) => ({ ...state, name }));
});