diff --git a/modules/store/spec/store.spec.ts b/modules/store/spec/store.spec.ts index eb9dd4a759..d756c9709a 100644 --- a/modules/store/spec/store.spec.ts +++ b/modules/store/spec/store.spec.ts @@ -534,24 +534,44 @@ describe('ngRx Store', () => { expect(metaReducerSpy2).toHaveBeenCalled(); }); - it('should create a meta reducer for feature and call it with the expected reducer', () => { + it('should create a meta reducer for feature and call it with the expected reducer', (done: DoneFn) => { + const counterReducer2Spy = jasmine + .createSpy('counterReducer2Spy', counterReducer2) + .and.callThrough(); + TestBed.configureTestingModule({ imports: [ StoreModule.forRoot({}), StoreModule.forFeature('counter1', counterReducer, { metaReducers: [metaReducerContainer.metaReducer1], }), - StoreModule.forFeature('counter2', counterReducer2, { - metaReducers: [metaReducerContainer.metaReducer2], - }), + StoreModule.forFeature( + 'counter2', + { counter: counterReducer2Spy }, + { + initialState: { counter: 2 }, + metaReducers: [metaReducerContainer.metaReducer2], + } + ), ], }); + const mockStore = TestBed.get(Store); const action = { type: INCREMENT }; + mockStore.dispatch(action); expect(metaReducerSpy1).toHaveBeenCalledWith(counterReducer); - expect(metaReducerSpy2).toHaveBeenCalledWith(counterReducer2); + expect(metaReducerSpy2).toHaveBeenCalled(); + expect(counterReducer2Spy).toHaveBeenCalledWith(2, action); + + mockStore.pipe(take(1)).subscribe({ + next(val: any) { + expect(val['counter2'].counter).toEqual(3); + }, + error: done, + complete: done, + }); }); }); diff --git a/modules/store/src/utils.ts b/modules/store/src/utils.ts index 7ded8a3810..7154a488d9 100644 --- a/modules/store/src/utils.ts +++ b/modules/store/src/utils.ts @@ -4,6 +4,7 @@ import { ActionReducerFactory, ActionReducerMap, MetaReducer, + InitialState, } from './models'; export function combineReducers( @@ -92,10 +93,17 @@ export function createReducerFactory( metaReducers?: MetaReducer[] ): ActionReducerFactory { if (Array.isArray(metaReducers) && metaReducers.length > 0) { - return compose.apply(null, [...metaReducers, reducerFactory]); + reducerFactory = compose.apply(null, [...metaReducers, reducerFactory]); } - return reducerFactory; + return (reducers: ActionReducerMap, initialState?: InitialState) => { + const reducer = reducerFactory(reducers, initialState); + + return (state: T | undefined, action: V) => { + state = state === undefined ? (initialState as T) : state; + return typeof reducer === 'function' ? reducer(state, action) : state; + }; + }; } export function createFeatureReducerFactory( @@ -107,6 +115,7 @@ export function createFeatureReducerFactory( : (r: ActionReducer) => r; return (reducer: ActionReducer, initialState?: T) => { + // I think this is also bug, shouldn't it be: reducerFactory(reducer, initialState)? reducer = reducerFactory(reducer); return (state: T | undefined, action: V) => {