updux/src/actions.test.ts

123 lines
3.0 KiB
TypeScript

import Updux, { createAction, withPayload } from './index.js';
test('basic action', () => {
const foo = createAction(
'foo',
withPayload((thing: string) => ({ thing })),
);
expect(foo('bar')).toEqual({
type: 'foo',
payload: {
thing: 'bar',
},
});
});
test('subduxes actions', () => {
const bar = createAction<number>('bar');
const baz = createAction('baz');
const foo = new Updux({
actions: {
bar,
},
subduxes: {
beta: {
actions: {
baz,
},
},
// to check if we can deal with empty actions
gamma: {},
},
});
expect(foo.actions).toHaveProperty('bar');
expect(foo.actions).toHaveProperty('baz');
expect(foo.actions.bar(2)).toHaveProperty('type', 'bar');
expect(foo.actions.baz()).toHaveProperty('type', 'baz');
});
test('Updux config accepts actions', () => {
const foo = new Updux({
actions: {
one: createAction(
'one',
withPayload((x) => ({ x })),
),
two: createAction(
'two',
withPayload((x) => x),
),
},
});
expect(Object.keys(foo.actions)).toHaveLength(2);
expect(foo.actions.one).toBeTypeOf('function');
expect(foo.actions.one('potato')).toEqual({
type: 'one',
payload: {
x: 'potato',
},
});
});
test('throw if double action', () => {
expect(
() =>
new Updux({
actions: {
foo: createAction('foo'),
},
subduxes: {
beta: {
actions: {
foo: createAction('foo'),
},
},
},
}),
).toThrow(/action 'foo' defined both locally and in subdux 'beta'/);
expect(
() =>
new Updux({
subduxes: {
gamma: {
actions: {
foo: createAction('foo'),
},
},
beta: {
actions: {
foo: createAction('foo'),
},
},
},
}),
).toThrow(/action 'foo' defined both in subduxes 'gamma' and 'beta'/);
});
test('action definition shortcut', () => {
const foo = new Updux({
actions: {
foo: 0,
bar: (x: number) => ({ x }),
baz: createAction('baz', withPayload<boolean>()),
},
});
expect(foo.actions.foo()).toEqual({ type: 'foo', payload: undefined });
expect(foo.actions.baz(false)).toEqual({
type: 'baz',
payload: false,
});
expect(foo.actions.bar(2)).toEqual({
type: 'bar',
payload: { x: 2 },
});
});