| 1 |
import { createEntityAdapter, createSlice } from '../..' |
| 2 |
import type { |
| 3 |
PayloadAction, |
| 4 |
Slice, |
| 5 |
SliceCaseReducers, |
| 6 |
UnknownAction, |
| 7 |
} from '../..' |
| 8 |
import type { EntityId, EntityState, IdSelector } from '../models' |
| 9 |
import type { BookModel } from './fixtures/book' |
| 10 |
|
| 11 |
describe('Entity Slice Enhancer', () => { |
| 12 |
let slice: Slice<EntityState<BookModel, BookModel['id']>> |
| 13 |
|
| 14 |
beforeEach(() => { |
| 15 |
const indieSlice = entitySliceEnhancer({ |
| 16 |
name: 'book', |
| 17 |
selectId: (book: BookModel) => book.id, |
| 18 |
}) |
| 19 |
slice = indieSlice |
| 20 |
}) |
| 21 |
|
| 22 |
it('exposes oneAdded', () => { |
| 23 |
const book = { |
| 24 |
id: '0', |
| 25 |
title: 'Der Steppenwolf', |
| 26 |
author: 'Herman Hesse', |
| 27 |
} |
| 28 |
const action = slice.actions.oneAdded(book) |
| 29 |
const oneAdded = slice.reducer(undefined, action as UnknownAction) |
| 30 |
expect(oneAdded.entities['0']).toBe(book) |
| 31 |
}) |
| 32 |
}) |
| 33 |
|
| 34 |
interface EntitySliceArgs<T, Id extends EntityId> { |
| 35 |
name: string |
| 36 |
selectId: IdSelector<T, Id> |
| 37 |
modelReducer?: SliceCaseReducers<T> |
| 38 |
} |
| 39 |
|
| 40 |
function entitySliceEnhancer<T, Id extends EntityId>({ |
| 41 |
name, |
| 42 |
selectId, |
| 43 |
modelReducer, |
| 44 |
}: EntitySliceArgs<T, Id>) { |
| 45 |
const modelAdapter = createEntityAdapter({ |
| 46 |
selectId, |
| 47 |
}) |
| 48 |
|
| 49 |
return createSlice({ |
| 50 |
name, |
| 51 |
initialState: modelAdapter.getInitialState(), |
| 52 |
reducers: { |
| 53 |
oneAdded(state, action: PayloadAction<T>) { |
| 54 |
modelAdapter.addOne(state, action.payload) |
| 55 |
}, |
| 56 |
...modelReducer, |
| 57 |
}, |
| 58 |
}) |
| 59 |
} |