updux/src/dux-selectors.test.js

70 lines
1.6 KiB
JavaScript

import { test, expect } from 'vitest';
import R from 'remeda';
import { dux, Updux } from './Updux.js';
import { matches } from './utils.js';
test('basic selectors', () => {
const foo = dux({
initial: {
x: 1,
},
selectors: {
getX: ({ x }) => x,
},
subduxes: {
bar: {
initial: { y: 2 },
selectors: {
getY: ({ y }) => y,
},
},
},
});
expect(foo.selectors.getY({ bar: { y: 3 } })).toBe(3);
});
test('splat selector', async () => {
const bar = new Updux({
initial: { id: 0, label: '' },
selectors: {
getLabel: R.prop('label'),
getLabelAppended: (state) => (suffix) => state.label + ' ' + suffix,
},
});
const foo = new Updux({
initial: [],
findSelectors: {
getBar: (state) => (id) => {
return state.find(matches({ id }));
},
},
selectors: {
getNbrBars: (state) => state.length,
},
subduxes: {
'*': bar,
},
});
const state = [
{ id: 1, label: 'one' },
{ id: 2, label: 'two' },
];
const store = foo.createStore(state);
expect(foo.selectors.getBar(state)(2).state).toMatchObject(state[1]);
expect(store.getState.getBar(2).state).toMatchObject(state[1]);
expect(store.getState.getNbrBars()).toBe(2);
expect(store.getState.getBar(1).getLabel()).toEqual('one');
expect(store.getState.getBar(1).getLabelAppended('plus one')).toEqual(
'one plus one',
);
});