|
| 1 | +import { createAction, createEntityAdapter, type EntityId } from '@reduxjs/toolkit' |
| 2 | + |
| 3 | +describe('createEntityAdapter', () => { |
| 4 | + describe('CRUD operations', () => { |
| 5 | + describe('upsertMany', () => { |
| 6 | + type Entity = { |
| 7 | + id: EntityId |
| 8 | + value?: string |
| 9 | + value2?: number |
| 10 | + } |
| 11 | + |
| 12 | + const entity1 = { id: 1 } |
| 13 | + const entity2 = { id: 2 } |
| 14 | + const update1 = { id: 1, value: 'hello' } |
| 15 | + const update2 = { id: 1, value: 'world' } |
| 16 | + const update3 = { id: 1, value2: 42 } |
| 17 | + const adapter = createEntityAdapter<Entity>() |
| 18 | + const anyAction = createAction<Entity[]>('anyAction') |
| 19 | + const { selectAll } = adapter.getSelectors() |
| 20 | + |
| 21 | + describe('when adding new entities', () => { |
| 22 | + const initialState = adapter.setOne(adapter.getInitialState({}), entity1) |
| 23 | + const upsertAction = anyAction([entity2]) |
| 24 | + |
| 25 | + it('should add a new entity to the state', () => { |
| 26 | + expect(selectAll(adapter.upsertMany(initialState, upsertAction))).toEqual([entity1, entity2]) |
| 27 | + }) |
| 28 | + }) |
| 29 | + |
| 30 | + describe('when updating existing entities', () => { |
| 31 | + const initialState = adapter.setOne(adapter.getInitialState({}), entity1) |
| 32 | + const upsertAction = anyAction([update1, update2, update3]) |
| 33 | + |
| 34 | + it('should update existing entity with multiple updates', () => { |
| 35 | + expect(selectAll(adapter.upsertMany(initialState, upsertAction))).toEqual([ |
| 36 | + Object.assign({}, entity1, update1, update2, update3), |
| 37 | + ]) |
| 38 | + }) |
| 39 | + }) |
| 40 | + |
| 41 | + describe('when applying updates to non-existing entities', () => { |
| 42 | + const initialState = adapter.getInitialState({}) |
| 43 | + const upsertAction = anyAction([update1, update2, update3]) |
| 44 | + |
| 45 | + it('should add the new entity and apply related updates', () => { |
| 46 | + expect(selectAll(adapter.upsertMany(initialState, upsertAction))).toEqual([ |
| 47 | + Object.assign({}, update1, update2, update3), |
| 48 | + ]) |
| 49 | + }) |
| 50 | + }) |
| 51 | + }) |
| 52 | + }) |
| 53 | +}) |
0 commit comments