|
| 1 | +import { createEntityAdapter, EntityAdapter } from './index' |
| 2 | +import { PayloadAction } from '../createAction' |
| 3 | +import { configureStore } from '../configureStore' |
| 4 | +import { createSlice } from '../createSlice' |
| 5 | +import { BookModel } from './fixtures/book' |
| 6 | + |
| 7 | +describe('createStateOperator', () => { |
| 8 | + let adapter: EntityAdapter<BookModel> |
| 9 | + |
| 10 | + beforeEach(() => { |
| 11 | + adapter = createEntityAdapter({ |
| 12 | + selectId: (book: BookModel) => book.id |
| 13 | + }) |
| 14 | + }) |
| 15 | + it('Correctly mutates a draft state when inside `createNextState', () => { |
| 16 | + const booksSlice = createSlice({ |
| 17 | + name: 'books', |
| 18 | + initialState: adapter.getInitialState(), |
| 19 | + reducers: { |
| 20 | + // We should be able to call an adapter method as a mutating helper in a larger reducer |
| 21 | + addOne(state, action: PayloadAction<BookModel>) { |
| 22 | + // Originally, having nested `produce` calls don't mutate `state` here as I would have expected. |
| 23 | + // (note that `state` here is actually an Immer Draft<S>, from `createReducer`) |
| 24 | + // One woarkound was to return the new plain result value instead |
| 25 | + // See https://github.com/immerjs/immer/issues/533 |
| 26 | + // However, after tweaking `createStateOperator` to check if the argument is a draft, |
| 27 | + // we can just treat the operator as strictly mutating, without returning a result, |
| 28 | + // and the result should be correct. |
| 29 | + const result = adapter.addOne(state, action) |
| 30 | + expect(result.ids.length).toBe(1) |
| 31 | + //Deliberately _don't_ return result |
| 32 | + }, |
| 33 | + // We should also be able to pass them individually as case reducers |
| 34 | + addAnother: adapter.addOne |
| 35 | + } |
| 36 | + }) |
| 37 | + |
| 38 | + const { addOne, addAnother } = booksSlice.actions |
| 39 | + |
| 40 | + const store = configureStore({ |
| 41 | + reducer: { |
| 42 | + books: booksSlice.reducer |
| 43 | + } |
| 44 | + }) |
| 45 | + |
| 46 | + const book1: BookModel = { id: 'a', title: 'First' } |
| 47 | + store.dispatch(addOne(book1)) |
| 48 | + |
| 49 | + const state1 = store.getState() |
| 50 | + expect(state1.books.ids.length).toBe(1) |
| 51 | + expect(state1.books.entities['a']).toBe(book1) |
| 52 | + |
| 53 | + const book2: BookModel = { id: 'b', title: 'Second' } |
| 54 | + store.dispatch(addAnother(book2)) |
| 55 | + |
| 56 | + const state2 = store.getState() |
| 57 | + expect(state2.books.ids.length).toBe(2) |
| 58 | + expect(state2.books.entities['b']).toBe(book2) |
| 59 | + }) |
| 60 | +}) |
0 commit comments