updux/src/mutations.test.ts
2024-08-08 11:51:49 -04:00

101 lines
2.5 KiB
TypeScript

import { createAction } from '@reduxjs/toolkit';
import { test, expect } from 'vitest';
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();
});